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
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
}
]
}
You could try
order = await Orders.find(...).toArray();
and then process the result as any array. Or is the resulting array of length one?