【问题标题】:How to multiple match in Mongo aggregation如何在 Mongo 聚合中进行多重匹配
【发布时间】:2020-10-03 01:43:38
【问题描述】:

我有一组Submission 文档。 每个Submission 都有一个bookingId,一个提交状态和一个指示,当状态为SUCCESS 时是否发送了事件

我正在尝试创建一个返回唯一 bookingId 列表的聚合。如果该 bookingId 的所有提交的状态为 SUCCESS,则此列表应包含 bookingId。

下面我有一组示例 Submission 文档:

{
    "_id" : ObjectId("5f7349ebc783305b9331a4b0"),
    "bookingId" : "NW111",
    "status" : "SUCCESS",
    "sent" : false
},
{
    "_id" : ObjectId("5f7349ebc783305b9331a4b1"),
    "bookingId" : "NW111",
    "status" : "SUCCESS",
    "sent" : false
},
{
    "_id" : ObjectId("5f7349ebc783305b9331a4b2"),
    "bookingId" : "NW115",
    "status" : "READY",
    "sent" : false
},
{
    "_id" : ObjectId("5f7349ebc783305b9331a4b3"),
    "bookingId" : "NW115",
    "status" : "PROCESSING",
    "sent" : false
},
{
    "_id" : ObjectId("5f7349ebc783305b9331a4b4"),
    "bookingId" : "NW115",
    "status" : "ERROR",
    "sent" : false
}

上述示例的预期结果应该是

{
    "bookingIds" : ["NW111"]
}

到目前为止,我有以下内容:

db.submissions.aggregate(
    [ { $match : { sent : false } } ]
);

【问题讨论】:

标签: mongodb aggregation-framework


【解决方案1】:

你可以试试,

  • $group by bookingId 并在状态为 SUCCESS 时在 status 中设置为 true,否则为 false
  • $match 条件状态不等于 false
  • $group 通过 null 并制作 bookingIds 的数组
db.submissions.aggregate([
  {
    $group: {
      _id: "$bookingId",
      status: {
        $addToSet: { $cond: [{ $eq: ["$status", "SUCCESS"] }, true, false] }
      }
    }
  },
  { $match: { status: { $ne: false } } },
  {
    $group: {
      _id: null,
      bookingIds: { $push: "$_id" }
    }
  }
])

Playground


第二种方法,如果你知道状态列表,那么你可以尝试,这样我们可以将$cond排除在第一组中,

  • $group by bookingId 并制作独特的状态数组
  • $match 状态不在提供的状态数组中
  • $group 通过 null 并制作 bookingIds 的数组
db.submissions.aggregate([
  {
    $group: {
      _id: "$bookingId",
      status: { $addToSet: "$status" }
    }
  },
  { $match: { status: { $nin: ["READY", "ERROR", "PROCESSING"] } } },
  {
    $group: {
      _id: null,
      bookingIds: { $push: "$_id" }
    }
  }
])

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多