I am having a response like this ....................................................................................................................................................................................................
{
"data": [
{
"user": "83k13bde05f40640j12075w",
"products": [
{
"type": "shoes",
"amount": 20
},
{
"type": "trousers",
"amount": 6
}
],
"inStock": false
},
{
"user": "9dc3f7de05f40640j12075y",
"products": [
{
"type": "chairs",
"amount": 11
},
{
"type": "bags",
"amount": 16
}
],
"inStock": false
},
{
"user": "6wb3f7ne35f40640m62p2gd",
"products": [
{
"type": "phones",
"amount": 2
},
{
"type": "clothes",
"amount": 15
}
],
"inStock": false
}
]
}
This the function outputting the above response
exports.getProducts = async (req,res) => {
const result = await Products
.find({inStock: false})
.select("-_id -createdAt -__v")
.exec()
if(!result) return res.status(400).json({ data: 'No product found' });
if(result.err) return res.json({ err: err });
return res.json({data: result});
}
But I want to get only products with the amount greater than 10
So my output should be like this
{
"data": [
{
"user": "83k13bde05f40640j12075w",
"products": [
{
"type": "shoes",
"amount": 20
}
],
"inStock": false
},
{
"user": "9dc3f7de05f40640j12075y",
"products": [
{
"type": "chairs",
"amount": 11
},
{
"type": "bags",
"amount": 16
}
],
"inStock": false
},
{
"user": "6wb3f7ne35f40640m62p2gd",
"products": [
{
"type": "clothes",
"amount": 15
}
],
"inStock": false
}
]
}
I tried using
.find({'products.amount': { $gt: 10 }})
But It didn't filter out the response
CodePudding user response:
Did you try the $elemMatch operator ?
const result = await Products
.find({
inStock: false,
products: { $elemMatch: { amount: { $gt: 10 } } }
})
.select("-_id -createdAt -__v")
.exec();
CodePudding user response:
You can use aggregation to achieve this. First of all you use $match operator to find the documents with items in the array that match with your criteria. Then you can use $project and $filter operator to return the array filtered.
const result = await Products.aggregate([
{
"$match" : {
"products" : {
"$elemMatch" : { amount: { $gt: 10 } }
},
}
},
{
$project: {
user: 1,
inStock: 1,
products: {
$filter: {
input: "$products",
as: "products",
cond: { $gt: ["$products.amount", 10] }
}
}
}
}
])
.select("-_id -createdAt -__v")
.exec();
For further reading: https://studio3t.com/knowledge-base/articles/filter-elements-from-mongodb-arrays/#how-to-use-filter-and-project