我有这样的React.........................................................................................................................
{
"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
}
]
}
这是输出上述响应的函数
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});
}
但我只想得到金额大于10的产品
所以输出应该是这样的
{
"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
}
]
}
我试着用
.find({'products.amount': { $gt: 10 }})
但它没有过滤掉
2条答案
按热度按时间e5nszbig1#
是否尝试了$elemMatch运算符?
aor9mmx12#
你可以使用聚合来实现这一点。首先你使用$match操作符来查找数组中的项目与你的条件匹配的文档。然后你可以使用$project和$filter操作符来返回过滤后的数组。
进一步阅读:https://studio3t.com/knowledge-base/articles/filter-elements-from-mongodb-arrays/#how-to-use-filter-and-project