首页 > 解决方案 > MongoDB查找包含具有连续匹配值的数组的所有对象

问题描述

我有一个 MongoDB 集合,如下所示:

{
  _id: "some-long-id-1"
  name: "John Doe",
  activities: [
    { name: "Lunch", status: "SCHEDULED" },
    { name: "Playing Football", status: "COMPLETED" },
    { name: "Workout", status: "COMPLETED" },
  ]
},
{
  _id: "some-long-id-2"
  name: "Jane Doe",
  activities: [
    { name: "Lunch", status: "COMPLETED" },
    { name: "Playing Football", status: "SCHEDULED" },
    { name: "Workout", status: "COMPLETED" },
  ]
}

我想查询所有activities包含至少一个连续COMPLETED状态的对象。例如,查询应该返回对象,因为它在活动数组中some-long-id-1具有连续的状态。COMPLETED它不应该返回some-long-id-2,因为即使有两个具有COMPLETED状态的数组但它们不是连续的。

标签: mongodbmongodb-query

解决方案


询问

  • 将数组减少为一个数字(计算我们找到的连续数)
    • 0 未找到
    • 1 找到一个
    • 2 找到 2
  • 我们需要reduce结果为= 2
  • if 2 => keep 2
    else if "completed" => inc the number
    else 0 (restart counts)

测试代码在这里

aggregate(
[{"$match": 
    {"$expr": 
      {"$eq": 
        [{"$reduce": 
            {"input": "$activities",
              "initialValue": 0,
              "in": 
              {"$switch": 
                {"branches": 
                  [{"case": {"$eq": ["$$value", 2]}, "then": "$$value"},
                    {"case": {"$eq": ["$$this.status", "COMPLETED"]},
                      "then": {"$add": ["$$value", 1]}}],
                  "default": 0}}}}, 2]}}}])

推荐阅读