arrays - 如何在 Mongoose 中查询 findOne() 以便我们获得满足特定条件的文档数组的子集?

标签 arrays node.js json mongodb mongoose

当我查询这个时

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 个条件

的任何文档
  1. 商店:req.shop.id
  2. "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/

相关文章:

asp.net - RESTful POST 重试响应

javascript - 在 ('request' 上)在每个请求上调用两次,为什么?

JSON 包含字符串和数组

c# 到 geojson 弹出项目括号 []

node.js - 连接到 websocket NodeJS Express 服务器时出错

ios - 带有参数的 NSMutableURLRequest - 无法解析响应

javascript - 根据数组类型键对对象数组进行分组

使用 '==' 运算符进行转换

c++ - 从随机起始位置开始的螺旋阵列

java - 添加两个字符数组并将结果作为字符存储在 Java 中的另一个字符数组中