Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda