Can I apply forEach in aggregate query in MongoDB?

2,939 views
Skip to first unread message

Shaishab Roy

unread,
Jul 21, 2016, 2:57:02 AM7/21/16
to mongodb-user
I have a member collection and find members by specific conditions and after get members I need to do some calculation for each member. To calculate need query on the same collection.

My process is

    var members = db.collection('member').find({ createdDate: currentDate, country: 'BD'}).toArray();
    members.forEach(function(doc) {
      var result = db.collection('member').aggregate([
        { $match: { memberType: doc.memberType, country : doc.country } },
        {
          $group: {
            _id: {memberType:"$memberType",country:"$country"},
            memberCount: { $sum: {$cond:[{$gt: ["$numberOfInvitees",0]},1,0]} },
            sameCount: { $sum: {$cond:[{$eq: ["$numberOfInvitees",doc.numberOfInvitees]},1,0]} }
          }
        }
      ]).toArray();
    });

**My question is how can I do this using single aggregate query?**

can any one help me pls :)

sjmi...@gmail.com

unread,
Jul 22, 2016, 2:18:05 AM7/22/16
to mongodb-user
You can add currentDate in _id for the group pipeline.
$group : {
           _id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" }, memberType:"$memberType",
country:"$country"
 }

https://docs.mongodb.com/manual/reference/operator/aggregation/group/

So now you will get summary for per day per your group in single query.

Chris Cunningham

unread,
Jul 29, 2016, 1:06:48 AM7/29/16
to mongodb-user

Shaishab,

This question was also posted on Stackoverflow and has been answered.

Thanks

Chris


Reply all
Reply to author
Forward
0 new messages