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

97
Views
map through array and return all matches mongodb

i want to map through array of Object that saved on MongoDB Database and return all indexes that matches with my condition...

for example, here is the the array..

orders: [
      {
        foodId: {
          type: mongoose.Types.ObjectId,
          ref: "Foods",
        },
        placeId: {
          type: mongoose.Types.ObjectId,
          required: true,
          ref: "Places",
        },
        qty: {
          type: Number,
          required: true,
          default: 1,
        },
        price: {
          type: Number,
          required: true,
        },
      },
    ],

i want to get all foods that orders from a place, i tried this query but didn't work and its only return first match and ignore rest of them.

//   HERE IS ORDERS COLLECTION, NOT ORDERS ARRAY THAT CONTAINS OBJECTS
    const order = await Orders.find({

//   HERE IS ORDERS ARRAY THAT CONTAINS THE OBJECTS
      orders: {
        $elemMatch: {
          placeId: mongoose.Types.ObjectId("610ae7be5867510cb43f0537"),
        },
      },
    })

this query only return first match, and ignore all after that

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

0

You can do it on the server using $filter The query bellow fitlers the orders array,and keep only the orders that have placeId=2

Data in

{
  "_id": 1,
  "orders": [
    {
      "foodId": 1,
      "placeId": 2,
      "qty": 3,
      "price": 4
    },
    {
      "foodId": 5,
      "placeId": 6,
      "qty": 7,
      "price": 8
    }
  ]
}

Query

aggregate(
[
  {
    "$addFields": {
      "orders": {
        "$filter": {
          "input": "$orders",
          "as": "order",
          "cond": {
            "$eq": [
              "$$order.placeId",
              2
            ]
          }
        }
      }
    }
  }
])

Results

{
  "_id": 1,
  "orders": [
    {
      "foodId": 1,
      "placeId": 2,
      "qty": 3,
      "price": 4
    }
  ]
}
about 4 years ago · Juan Pablo Isaza Report

0

You could try

order = await Orders.find(...).toArray();

and then process the result as any array. Or is the resulting array of length one?

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!