Hardik Gondalia
Hardik Gondalia

Reputation: 3717

Group by in mongoose gives multiple record

I am trying to apply group by aggregation in mongoose by following code

app.get('/api/get_conversation_all_carer/:carer_id',function(req,res){
        //Sender = user and receiver = carer
        var data = [];
        var conversation = {status_code:200, data:data};
        Conversation.find({'receiver_id': req.params.carer_id},{sender_id:1},{'group': 'sender_id'},function(err,result)
        {
            console.log(result);
        });
    });

which gives me following output

[{ _id: 561f985439365e3c2aa9398a,
    sender_id: '55f000a2878075c416ff9879' },
  { _id: 5620cfd0e4b0b1432a7331bb,
    sender_id: '55f000a2878075c416ff9879' }]

Here for same sender_id why I am getting two separate record.
I want just sender_id like
[{sender_id: '55f000a2878075c416ff9879'}]

Upvotes: 2

Views: 354

Answers (2)

Blakes Seven
Blakes Seven

Reputation: 50406

You want .aggregate() which is a modern version and does better document manipulation in native code without JavaScript execution or translation. I supspect you already found $group in the documentation, but did not realize it is tied to .aggregate() and not the .find() method:

Conversation.aggregate(
    [
        { "$match": { "receiver_id": req.params.carer_id },
        { "$group": { "_id": "$sender_id" } }
    ],
    function(err,result) {
        console.log(result);
    }
);

Which will return an array of results for the distinct values of the field referenced in the "key" _id for $group, ( even if only one ) like this:

[{_id: '55f000a2878075c416ff9879'}]

You can optionally exchange _id for sender_id using $project, but it's not a good habit to get into, and rather just make your receiving logic accept the "unique key" is always named _id instead.

Upvotes: 2

Nikola B.
Nikola B.

Reputation: 606

Try using db.collection.group():

Conversation.collection.group(
{
    key: {sender_id:1},
    cond: {receiver_id: req.params.carer_id},
    reduce: function ( curr, result ) { },
    initial: { },
    function(err, results){
        console.log(result);
    }
});

Upvotes: 0

Related Questions