【发布时间】:2013-02-13 13:14:21
【问题描述】:
我在子文档中有这样的数组
{
"_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
}
]
}
我可以过滤数组中的元素以获得预期结果吗?
【问题讨论】:
标签: mongodb filter mongodb-query aggregation-framework