使用多个过滤器在对象数组上查询 MongoDB

问题描述 投票:0回答:1

Users
集合中,我们有一个数组字段
events
,它存储不同类别的事件。这是一个包含 2 个字段的对象数组:
event
category

我们尝试在 MongoDB 中设置一个查询,根据两个条件获取用户列表:

  • 首先,我们要过滤
    events
    至少有 1 个具有“分析”类别的事件
  • 然后,我们要在过滤后的数组中过滤
    events
    ,其最后一个具有“Analytics”类别的事件是“Views”。

举个例子:

[{
 _id: "123",
 events:[{
  category: "Payment"
  event: "ok",
 },
{
  category: "Analytics"
  event: "Views"
 },
{
  category: "Analytics"
  event: "Clicks"
 }]
},
{
 _id: "456",
 events:[{
  category: "Payment"
  event: "ok"
 },
{
  category: "Analytics"
  event: "Clicks"
 },

  category: "Payment"
  event: "failed"
 }]
}]

结果应该是:

[{
 _id: "123",
 events:[{
  category: "Payment"
  event: "ok"
 },
{
  category: "Analytics"
  event: "Views"
 },
{
  category: "Analytics"
  event: "Clicks"
 }]
}]

我们尝试基于聚合和分组的查询,但它不起作用:

db.users.aggregate([
  {
    $match: {
      "users.events.category": "Analyics",
      "users.events.event": "Views"
    }
  },
  {
    $group: {
      _id: "$_id",
      shipment: { $first: "$$ROOT" }
    }
  },
  {
    $replaceRoot: { newRoot: "$shipment" }
  }
])

您知道如何解决我们的问题吗?

arrays mongodb mongodb-query aggregate
1个回答
0
投票

我想你想要这样的东西:

db.users.aggregate([
  {
    $match: {
      $and: [
        {
          "events.category": "Analytics"
        },
        {
          $expr: {
            $eq: [
              {
                $last: "$events.event"
              },
              "Views"
            ]
          }
        }
      ]
    }
  }
])
© www.soinside.com 2019 - 2024. All rights reserved.