Random record from MongoDB

Starting with the 3.2 release of MongoDB, you can get N random docs from a collection using the $sample aggregation pipeline operator: // Get one random document from the mycoll collection. db.mycoll.aggregate([{ $sample: { size: 1 } }]) If you want to select the random document(s) from a filtered subset of the collection, prepend a … Read more

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