MongoDB 聚合过滤器返回 null

布里尼

在 MongoDB 中,我有一个消息集合(在下面找到):

我感兴趣的是通过查询ID父文档,并说过滤contactedNumberMessages,只包括传入消息(那些方向“中”),所以我写了猫鼬下面的代码,不过contactedNumberMessagesnull在返回的数据,任何线索,为什么我得到null吗?谢谢

Messages.aggregate([
    {
      $match: {
        _id: id
      }
    },
    {
      $project: {
        messaging: {
          ourNumber: 1,
          messages: {
            contact: 1,
            contactedNumberMessages: {
              $filter: {
                input: "$contactedNumberMessages",
                as: "message",
                cond: {
                  $eq: ["$$message.direction", "out"]
                }
              }
            }
          }
        }
      }
    }
  ]);
{
  "_id": {
    "$oid": "612f4e32aa56064f1608c2eb"
  },
  "messaging": [
    {
      "ourNumber": "+15123568549",
      "messages": [
        {
          "contact": "+21629000111",
          "contactedNumberMessages": [
            {
              "direction": "out",
              "content": "Hello!",
              "when": {
                "$date": "2021-09-23T23:00:00.000Z"
              },
              "nature": "SMS"
            },
            {
              "direction": "in",
              "content": "Hi!",
              "when": {
                "$date": "2021-09-23T23:00:00.000Z"
              },
              "nature": "SMS"
            }
          ]
        }
      ]
    }
  ]
}
程序员分析师

请参考这里的例子:https : //mongoplayground.net/p/9toRoa_5IE9

您应该在聚合中使用如下所示的内容:

[{$match: {
  _id: ObjectId('612f4e32aa56064f1608c2eb')
}}, {$unwind: {
  path: '$messaging',
}}, {$unwind: {
  path: '$messaging.messages',
}}, {$project: {
        messaging: {
    ourNumber: 1,
    messages: {
      contact: 1,
      contactedNumberMessages: {
        $filter: {
          input: "$messaging.messages.contactedNumberMessages",
          as: "message",
          cond: {
            $eq: ["$$message.direction", "out"]
          }
        }
      }
    }
  }
}}]

由于您在数组和子数组中嵌套数组,过滤阶段没有获得正确的输出,我添加了 unwind 以获得 field:messaging.messages.contactedNumberMessages 的正常数组

如果需要,您可以再次执行 groupby 以确保获得预期格式的文档,因为展开后它将为展开的数组中的每个文档创建多个聚合文档。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章