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

159
Views
prevent duplicated values mongodb find query

(javascript)

hello, i have a mongodb collection who have this schema:

{
  _id: "any",
  ids: {
     user: "some value who can repeat" // and more keys but i will use this key here
  },
  time: 400 // can vary
}

I need to get some documents from this collection, filter to "time less than 700" and dont repeat the key "user"

I tried to use js tools for this, but in only 1 find query i get +900 documents

const ids = [];

const query = (await Personagens.find({ time: { $lt: 700 }}).sort({ time: 1 }))
.filter(x => {
    if (!ids.includes(x.ids.user)) {
        ids.push(x.ids.user);
        return true;
    }
}).slice(0, 50)

the output who shows +900 documents in 1 query

so i want to know if has some mongo db operator to filter repeated keys (the key ids.user) and get only 50 documents (obs: i use mongoose)

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

0

db.collection.aggregate([
  {
    "$match": {
      time: {
        "$gt": 700
      }
    }
  },
  {
    "$group": {
      "_id": "$ids.user",
      "doc": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$set": {
      "doc": {
        "$first": "$doc"
      }
    }
  },
  {
    "$replaceWith": "$doc"
  }
])

mongoplayground

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!