Mongodb Aggregation : How to return only matching elements of an array [duplicate]
You could do this with the 2.2 aggregation framework. Something like this;
db.books.runCommand("aggregate", { pipeline: [ { // find docs that contain Par* $match: { "indexTokens" : { "$regex" : "^Par" , "$options" : "i"}}, }, { // create a doc with a single array elemm for each indexToken entry $unwind: "$indexTokens" }, { // now produce a list of index tokens $group: { _id: "$indexTokens", }, }, ],})
Or this might be even closer to what you're after if you really want the array without the doc;
db.books.runCommand("aggregate", { pipeline: [ { // find docs that contain Par* $match: { "indexTokens" : { "$regex" : "^Par" , "$options" : "i"}}, }, { // create a doc with a single array elemm for each indexToken entry $unwind: "$indexTokens" }, { // now throw out any unwind's that DON'T contain Par* $match: { "indexTokens": { "$regex": "^Par", "$options": "i" } }, }, { // now produce the list of index tokens $group: { _id: null, indexTokens: { $push: "$indexTokens" }, }, }, ],})
Building on the response from cirrus, I recommend doing the $unwind
first to avoid the redundant $match
. Something like:
db.books.aggregate( {$unwind:"$indexTokens"}, {$match:{indexTokens:/^Par/}}, {$group:{_id:null,indexTokens:{$push:"$indexTokens"}}})
How do you do this in Java? You can use the DBCollection.aggregate(...)
method of the MongoDB v2.9.0 driver. Each pipeline operator, eg. $unwind
or $match
, corresponds to a DBObject
object.