How to filter array in subdocument with MongoDB [duplicate]

Using aggregate is the right approach, but you need to $unwind the list array before applying the $match so that you can filter individual elements and then use $group to put it back together: db.test.aggregate([ { $match: {_id: ObjectId(“512e28984815cbfcb21646a7”)}}, { $unwind: ‘$list’}, { $match: {‘list.a’: {$gt: 3}}}, { $group: {_id: ‘$_id’, list: {$push: ‘$list.a’}}} ]) … Read more

Get names of all keys in the collection

You could do this with MapReduce: mr = db.runCommand({ “mapreduce” : “my_collection”, “map” : function() { for (var key in this) { emit(key, null); } }, “reduce” : function(key, stuff) { return null; }, “out”: “my_collection” + “_keys” }) Then run distinct on the resulting collection so as to find all the keys: db[mr.result].distinct(“_id”) [“foo”, … Read more

Group result by 15 minutes time interval in MongoDb

There are a couple of ways to do this. The first is with Date Aggregation Operators, which allow you to dissect the “date” values in documents. Specifically for “grouping” as the primary intent: db.collection.aggregate([ { “$group”: { “_id”: { “year”: { “$year”: “$created_at” }, “dayOfYear”: { “$dayOfYear”: “$created_at” }, “hour”: { “$hour”: “$created_at” }, “interval”: … Read more

Retrieve only the queried element in an object array in MongoDB collection

MongoDB 2.2’s new $elemMatch projection operator provides another way to alter the returned document to contain only the first matched shapes element: db.test.find( {“shapes.color”: “red”}, {_id: 0, shapes: {$elemMatch: {color: “red”}}}); Returns: {“shapes” : [{“shape”: “circle”, “color”: “red”}]} In 2.2 you can also do this using the $ projection operator, where the $ in a … Read more