Conditional $sum in MongoDB

As Sammaye suggested, you need to use the $cond aggregation projection operator to do this: db.Sentiments.aggregate( { $project: { _id: 0, Company: 1, PosSentiment: {$cond: [{$gt: [‘$Sentiment’, 0]}, ‘$Sentiment’, 0]}, NegSentiment: {$cond: [{$lt: [‘$Sentiment’, 0]}, ‘$Sentiment’, 0]} }}, { $group: { _id: “$Company”, SumPosSentiment: {$sum: ‘$PosSentiment’}, SumNegSentiment: {$sum: ‘$NegSentiment’} }});

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

Moongoose aggregate $match does not match id’s

Your ids variable will be constructed of “strings”, and not ObjectId values. Mongoose “autocasts” string values for ObjectId into their correct type in regular queries, but this does not happen in the aggregation pipeline, as in described in issue #1399. Instead you must do the correct casting to type manually: ids = ids.map(function(el) { return … Read more

MongoDB: Combine data from multiple collections into one..how?

MongoDB 3.2 now allows one to combine data from multiple collections into one through the $lookup aggregation stage. As a practical example, lets say that you have data about books split into two different collections. First collection, called books, having the following data: { “isbn”: “978-3-16-148410-0”, “title”: “Some cool book”, “author”: “John Doe” } { … Read more