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

217
Vistas
How to get documents queried by array of IDs regardless if the ID's in the array exists more than once

I just discovered that I can iterate find() in mongoose without using a loop. By doing this.

    const arrOfIds = reqBody.items.map(item => item.productId);


    Product.find({ '_id': { $in: arrOfIds }},(error, result)=>{


    const productList = collect(result).toArray();


})

However my problem is, if there's an id in the array(arrOfIds) that exists more than once, the find() method only treat that as one existence thus that is not correct since I want to sum the prices for this products, duplicate or not.

My previous code was using a map() to loop find() and then calculate sum but got complicated with other codes, I just want simpler method using this one. Can I get it to work to return the document for each IDs, regardless of having duplicates?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

let say arrOfIds is ["product1", "product4", "product3", "product1", "product1" ] then you can use below aggregation pls refer to https://mongoplayground.net/p/1DtTtZWCHaH

db.collection.aggregate([
  {
    "$match": {
      _id: {
        $in: [
          "product1",
          "product4",
          "product3",
          "product1",
          "product1"
        ]
      }
    }
  },
  {
    "$set": {
      "totalPrice": {
        "$function": {
          "body": "function(arrOfIds,_id,price) {try { var total=0; arrOfIds.forEach((entry) => { if (entry=== _id){total= total+price;}})} catch (e) {row_number= 0;}return total;}",
          "args": [
            [
              "product1",
              "product4",
              "product3",
              "product1",
              "product1"
            ],
            "$_id",
            "$price"
          ],
          "lang": "js"
        }
      }
    }
  }
])

where we match product based on our array and then we set total price based on the number of occurrences using set by implementing function with logic to do for each! its still foreach/loop but on server side

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