如何用MongoDB过滤子文档中的数组我在子文档中有这样的数组{
"_id" : ObjectId("512e28984815cbfcb21646a7"),
"list" : [
{
"a" : 1
},
{
"a" : 2
},
{
"a" : 3
},
{
"a" : 4
},
{
"a" : 5
}
]}我能过滤一个>3的子文档吗?我的预期结果如下{
"_id" : ObjectId("512e28984815cbfcb21646a7"),
"list" : [
{
"a" : 4
},
{
"a" : 5
}
]}我试着用$elemMatch但是返回数组中的第一个匹配元素。我的问题是:db.test.find( { _id" : ObjectId("512e28984815cbfcb21646a7") }, {
list: {
$elemMatch:
{ a: { $gt:3 }
}
} } )结果返回数组中的一个元素。{ "_id" : ObjectId("512e28984815cbfcb21646a7"), "list" : [ { "a" : 4 } ] }我试着用聚合$match但不工作db.test.aggregate({$match:{_id:ObjectId("512e28984815cbfcb21646a7"), 'list.a':{$gte:5} }})它返回数组中的所有元素{
"_id" : ObjectId("512e28984815cbfcb21646a7"),
"list" : [
{
"a" : 1
},
{
"a" : 2
},
{
"a" : 3
},
{
"a" : 4
},
{
"a" : 5
}
]}我能过滤数组中的元素以得到预期的结果吗?
3 回答
哆啦的时光机
TA贡献1779条经验 获得超6个赞
aggregate$unwindlist$match$group
db.test.aggregate(
{ $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
{ $unwind: '$list'},
{ $match: {'list.a': {$gt: 3}}},
{ $group: {_id: '$_id', list: {$push: '$list.a'}}}){
"result": [
{
"_id": ObjectId("512e28984815cbfcb21646a7"),
"list": [
4,
5
]
}
],
"ok": 1}MongoDB 3.2更新
$filterlist$project:
db.test.aggregate([
{ $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
{ $project: {
list: {$filter: {
input: '$list',
as: 'item',
cond: {$gt: ['$$item.a', 3]}
}}
}}])
拉丁的传说
TA贡献1789条经验 获得超8个赞
db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1}){
"_id": ObjectId("..."),
"list": [{a: 1}]}
守候你守候我
TA贡献1802条经验 获得超10个赞
根据指定的条件选择要返回的数组的子集。返回只包含与条件匹配的元素的数组。返回的元素按原来的顺序排列。
db.test.aggregate([
{$match: {"list.a": {$gt:3}}}, // <-- match only the document which have a matching element
{$project: {
list: {$filter: {
input: "$list",
as: "list",
cond: {$gt: ["$$list.a", 3]} //<-- filter sub-array based on condition
}}
}}]);- 3 回答
- 0 关注
- 2111 浏览
添加回答
举报
0/150
提交
取消
