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

212
Views
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 answers
Answer question

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 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!