Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda