如何用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 關注
- 2052 瀏覽
添加回答
舉報
0/150
提交
取消
