Posts

Showing posts with the label Aggregation Framework

Convert Milliseconds To Date In Mongodb Aggregation Pipeline For Group By?

Answer : I'm trying to get the logic behind converting the txnTime field to a date object because grouping by either a date field or a timestamp in milliseconds (like what you are presently doing) will yield the same result as they both are unique in their respective formats! To change the txnTime field to a date object you should then include a $project pipeline before the $group pipeline stage with this expression "txnTime": { "$add": [ new Date(0), "$txnTime" ] } so that you can do your $group operation on the converted/projected txnTime field: var convertedTxnTime = { "$add": [new Date(0), "$txnTime"] }; /* If using MongoDB 4.0 and newer, use $toDate var convertedTxnTime = { "$toDate": "$txnTime" }; or $convert var convertedTxnTime = { "$convert": { "input": "$txnTime", "to": "date" } }; */ db.campaign_wallet.aggregate([ { "$match...

Conditional $sum In MongoDB

Answer : 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'} }}); Starting from version 3.4, we can use the $switch operator which allows logical condition processing in the $group stage. Of course we still need to use the $sum accumulator to return the sum. db.Sentiments.aggregate( [ { "$group": { "_id": "$Company", "SumPosSenti": { "$sum": { "$switch": { ...