How To Query Unique Users With Mongoose

Viewed 54

Context
In a MongoDB database, I have a collection with mail documents inside. Each document has receiver and sender fields.

Goal
I want to query for one mail from each sender. In other words, I do not want two or more mail from the same sender.

Example
I have three documents:

{
    _id: 1,
    sender: John,
    receiver: Kate
}

{
    _id: 2,
    sender: John,
    receiver: Kate
}

{
    _id: 3,
    sender: Mike,
    receiver: Kate
}

After the query, I should end up with: (the second mail from John is not included)

{
    _id: 1,
    sender: John,
    receiver: Kate
}

{
    _id: 3,
    sender: Mike,
    receiver: Kate
}

Please help! Thanks.

1 Answers

use this aggregation, group by sender and push receiver to array then put receiver as first element of array

db.collection.aggregate([
  {
    $group: {
      _id: {
        "sender": "$sender"
      },
      r: {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$project": {
      sender: "$_id.sender",
      receiver: {
        $first: "$r.receiver"
      },
      description: {
        $first: "$r.description"
      },
      _id: 0
    }
  }
])

https://mongoplayground.net/p/mwDdL4aLneu

Related