Monday, 29 May 2017

Mongoose aggregate get list of _ids with group

I would like to group a list of documents in mongodb and at the same time return all the unique ids that belong to that group.

Users.aggregate([
            {
                $group: {
                        "ids": { $addToSet: "$_id"},
                        "_id": "$_id",
                        "from": {$first: "$from"},
                        "type":  {$first: "$type"},
                        "status": {$first: "$status"},


                },

            },
            {
                $project: {
                    "_id": 1,
                    "from": 1,
                    "type": 1,
                    "status": 1,
                    "ids": 1,
                }
            },
        ]);

What i get is this:

{
 _id: 592bf783b80a211b681e2ec9,
  ids: [ 592bf783b80a211b681e2ec9 ],
  from: 'New York',
  type: 'user',
  status: 'Active'
}

I would like to perform a simple task on each user grouped by the "from" field and apply the results for all the users one by one who was found in the previous query.

What i would like to receive is something like:

{ _id: 592bf783b80a211b681e2ec9, ids: [ 592bf783b80a211b681e2ec9, 592bf78456435634643c9, asd78f880a211b681e2ec9 ], from: 'New York', type: 'user', status: 'Active' }



via Azarus

No comments:

Post a Comment