为什么$elemMatch返回第一个文档,而不是所有匹配的文档



我正在尝试执行一个查询,该查询返回基于查询参数匹配的所有文档。

我有以下模式:

_id: ObjectId('631b875491b16c38eecfa4e9')
brandName: "Nick"
categories: Array
products: Array
0: Object
productName: "Vans Shoes dsds Old Skool"
description: "amazing Shoes."
categoryId: ObjectId('62f3eaff3ded19dcce71081e')
price: 240
numberOfBuyers: 0
_id: ObjectId(631b875491b16c38eecfa4ec)
1: Object
2: Object
3: Object
__v: 0

下面的查询应该给我所有匹配的文档,但它只返回第一个文档:

const products = await Brand.find(
{
_id: brandId
},
{
products: {
$elemMatch: {
categoryId: categoryId,
price: {
$gte: minPrice,
$lte: maxPrice
}
}
}
})

怎么了?

您正在查询"品牌"文件。这意味着您的查询告诉Mongoose:如果其中一个产品匹配(categoryId和price(,则返回(整个(Brand文档。

为了只检索这个数组的特定元素,您应该在find调用的投影步骤中包括$elemMatch对象:

const products = await Brand.find({
_id: brandId 
}, {
//include other properties you want to include in your output document
products: {
$elemMatch: {
categoryId: "62f3eaff3ded19dcce71081e",
price: 240
}
}
}
})

评论后更新您的产品数组将只包含匹配的第一个元素。这是预期行为(如本文所述:cs/manual/reference/operator/project/elemMatch/(:

定义$elemMatch这个$elemMatch运算符将查询结果中字段的内容限制为仅包含与$elemMatch条件

为了获得多个结果,您可能应该使用使用$unwind$group的聚合管道。

最新更新