如何用MongoDB過(guò)濾子文檔中的數(shù)組我在子文檔中有這樣的數(shù)組{
"_id" : ObjectId("512e28984815cbfcb21646a7"),
"list" : [
{
"a" : 1
},
{
"a" : 2
},
{
"a" : 3
},
{
"a" : 4
},
{
"a" : 5
}
]}我能過(guò)濾一個(gè)>3的子文檔嗎?我的預(yù)期結(jié)果如下{
"_id" : ObjectId("512e28984815cbfcb21646a7"),
"list" : [
{
"a" : 4
},
{
"a" : 5
}
]}我試著用$elemMatch但是返回?cái)?shù)組中的第一個(gè)匹配元素。我的問(wèn)題是:db.test.find( { _id" : ObjectId("512e28984815cbfcb21646a7") }, {
list: {
$elemMatch:
{ a: { $gt:3 }
}
} } )結(jié)果返回?cái)?shù)組中的一個(gè)元素。{ "_id" : ObjectId("512e28984815cbfcb21646a7"), "list" : [ { "a" : 4 } ] }我試著用聚合$match但不工作db.test.aggregate({$match:{_id:ObjectId("512e28984815cbfcb21646a7"), 'list.a':{$gte:5} }})它返回?cái)?shù)組中的所有元素{
"_id" : ObjectId("512e28984815cbfcb21646a7"),
"list" : [
{
"a" : 1
},
{
"a" : 2
},
{
"a" : 3
},
{
"a" : 4
},
{
"a" : 5
}
]}我能過(guò)濾數(shù)組中的元素以得到預(yù)期的結(jié)果嗎?
3 回答
哆啦的時(shí)光機(jī)
TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
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]}
}}
}}])
拉丁的傳說(shuō)
TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1}){
"_id": ObjectId("..."),
"list": [{a: 1}]}
守候你守候我
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
根據(jù)指定的條件選擇要返回的數(shù)組的子集。返回只包含與條件匹配的元素的數(shù)組。返回的元素按原來(lái)的順序排列。
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 關(guān)注
- 2071 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
