当我查询这个时
constendingOfThisShop=awaitShopProfile.findOne({shop:req.shop.id,"shopsAffiliate.status":"pending"},{shopsAffiliate:1,_id:0}
我得到一个像这样的对象
{
"shopsAffiliate": [
{
"status": "approved",
"_id": "5db315a6de255a4444b0987b",
"affiliateId": "5db31263a362ed4ed84c7ad5"
},
{
"status": "pending",
"_id": "5db315c5de255a4444b0987d",
"affiliateId": "5db2b4713db4101e48836f0a"
}
]}
我同时获得状态:“已批准”和状态:“待处理”。我只想获取 shopAffiliate 数组中状态为“pending”的对象。我该怎么办?
最佳答案
I get both status:"approved" and status:"pending"
您的查询正在返回预期结果。
shopsAffiliate
是嵌套文档的数组。 shopsAffiliate
本身是 ShopProfile
集合中文档的一部分。您的查询会检查 ShopProfile
中是否存在满足以下 2 个条件
商店:req.shop.id
"shopsAffiliate.status":"待处理"
当它找到任何符合上述条件的文档时,它会返回整个文档。它不关心匹配文档的 shopsAffiliate
数组中是否还有其他不具有 pending
状态的文档,它只需要在其中找到至少 1 个文档具有 pending
状态的 shopsAffiliate
数组,一旦找到,就会返回整个文档。
I only want to get those objects in shopsAffiliate array which have status of "pending". What should I do?
您可以使用aggregation operation得到想要的结果
const pendingOfThisShop = await ShopProfile.aggregate([
{
$match: {
shop: req.shop.id,
"shopsAffiliate.status": "pending"
}
},
{
$unwind: "$shopsAffiliate"
},
{
$match: { "shopsAffiliate.status": "pending" }
}
]);
关于arrays - 如何在 Mongoose 中查询 findOne() 以便我们获得满足特定条件的文档数组的子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563452/