How to filter array in subdocument with MongoDB -
this question has answer here:
i have array in subdocument this
{ "_id" : objectid("512e28984815cbfcb21646a7"), "list" : [ { "a" : 1 }, { "a" : 2 }, { "a" : 3 }, { "a" : 4 }, { "a" : 5 } ] }
can filter subdocument > 3
my expect result below
{ "_id" : objectid("512e28984815cbfcb21646a7"), "list" : [ { "a" : 4 }, { "a" : 5 } ] }
i try use $elemmatch
returns first matching element in array
my query:
db.test.find( { _id" : objectid("512e28984815cbfcb21646a7") }, { list: { $elemmatch: { a: { $gt:3 } } } } )
the result return 1 element in array
{ "_id" : objectid("512e28984815cbfcb21646a7"), "list" : [ { "a" : 4 } ] }
and try use aggregate $match
not work
db.test.aggregate({$match:{_id:objectid("512e28984815cbfcb21646a7"), 'list.a':{$gte:5} }})
it's return element in array
{ "_id" : objectid("512e28984815cbfcb21646a7"), "list" : [ { "a" : 1 }, { "a" : 2 }, { "a" : 3 }, { "a" : 4 }, { "a" : 5 } ] }
can filter element in array result expect result?
using aggregate
right approach, need $unwind
list
array before applying $match
can filter individual elements , use $group
put together:
db.test.aggregate( { $match: {_id: objectid("512e28984815cbfcb21646a7")}}, { $unwind: '$list'}, { $match: {'list.a': {$gt: 3}}}, { $group: {_id: '$_id', list: {$push: '$list.a'}}})
outputs:
{ "result": [ { "_id": objectid("512e28984815cbfcb21646a7"), "list": [ 4, 5 ] } ], "ok": 1 }
mongodb 3.2 update
starting 3.2 release, can use new $filter
aggregation operator more efficiently including list
elements want during $project
:
db.test.aggregate([ { $match: {_id: objectid("512e28984815cbfcb21646a7")}}, { $project: { list: {$filter: { input: '$list', as: 'item', cond: {$gt: ['$$item.a', 3]} }} }} ])
Comments
Post a Comment