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

Group count with MongoDB using aggregation framework

To accommodate the potential duplicates, you need to use two $group operations: db.test.aggregate([ { $group: { _id: { owner_id: ‘$owner_id’, car_id: ‘$car_id’ } }}, { $group: { _id: ‘$_id.owner_id’, cars_owned: { $sum: 1 } }}, { $project: { _id: 0, owner_id: ‘$_id’, cars_owned: 1 }}] , function(err, result){ console.log(result); } ); Gives a result with … Read more

Mongodb sort inner array

You can do this by $unwinding the updates array, sorting the resulting docs by date, and then $grouping them back together on _id using the sorted order. db.servers.aggregate( {$unwind: ‘$service.apps.updates’}, {$sort: {‘service.apps.updates.date’: 1}}, {$group: {_id: ‘$_id’, ‘updates’: {$push: ‘$service.apps.updates’}}}, {$project: {‘service.apps.updates’: ‘$updates’}})

Find in Double Nested Array MongoDB

In the simplest sense this just follows the basic form of “dot notation” as used by MongoDB. That will work regardless of which array member the inner array member is in, as long as it matches a value: db.mycollection.find({ “someArray.someNestedArray.name”: “value” }) That is fine for a “single field” value, for matching multiple-fields you would … Read more

Multiple join conditions using the $lookup operator

We can do multiple join conditions with the $lookup aggregation pipeline operator in version 3.6 and newer. We need to assign the fields’s values to variable using the let optional field; you then access those variables in the pipeline field stages where you specify the pipeline to run on the collections. Note that in the … Read more