Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
How To Query Unique Users With Mongoose

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!