根据状态筛选 mongoDb 中的结果

Filter results in mongoDb based on status

我有一个这样的数组

[
{
    "name": "CAMP-1",
    "status": "incomplete",
    "version": 3,
  },
  {
    "name": "CAMP-1",
    "status": "complete",
    "version": 2,
  },
  {
    "name": "CAMP-1",
    "status": "complete",
    "version": 1,
  },
  {
    "name": "CAMP-2",
    "status": "complete",
    "version": 2,
  },
{
    "name": "CAMP-2",
    "status": "incomplete",
    "version": 1,
  }
]

如果最新版本的状态不完整,则应返回最新的不完整和完整版本。

如果最新版本的状态是完整的,则只应返回该版本。

我尝试按名称和状态分组,这给出了不完整和完整对象的最新版本

db.collection.aggregate({
  "$sort": {
    "version": -1
  }
},
{
  "$group": {
    "_id": {
      "content": "$name",
      "status": "$status"
    },
    "status": {
      "$first": "$$ROOT"
    },
    "content": {
      "$first": "$$ROOT"
    }
  }
},
{
  "$replaceRoot": {
    "newRoot": "$content"
  }
})

我得到的输出是

[
{
    "name": "CAMP-1",
    "status": "incomplete",
    "version": 3,
  },
{
    "name": "CAMP-1",
    "status": "complete",
    "version": 2,
  },
  {
    "name": "CAMP-1",
    "status": "complete",
    "version": 1,
  },
{
    "name": "CAMP-2",
    "status": "incomplete",
    "version": 2,
  }
]

但预期的输出是

[
{
    "name": "CAMP-1",
    "status": "incomplete",
    "version": 3,
  },
{
    "name": "CAMP-1",
    "status": "complete",
    "version": 2,
  },
{
    "name": "CAMP-2",
    "status": "complete",
    "version": 2,
  }
]

任何人都可以帮助了解如何根据状态过滤数据吗?

查询

  • 按名称分组
  • 找到 max-complete 版本
  • 过滤保持完成的版本相同,未完成的版本更大
  • 展开并替换 root

*例如,对于 1 个名称,如果您有不完整的版本 5 6 7 3 和完整的 2 3 4 ,您将得到 5 6 7 不完整的和 4 个完整的。
如果它不是您想要的,也许只需稍作改动,您就可以得到您需要的。

Playmongo(看看每个阶段做了什么把鼠标放在最后)

aggregate(
[{"$group": {"_id": "$name", "docs": {"$push": "$$ROOT"}}},
 {"$set": 
   {"max-complete": 
     {"$let": 
       {"vars": 
         {"c": 
           {"$filter": 
             {"input": "$docs",
              "cond": {"$eq": ["$$this.status", "complete"]}}}},
        "in": {"$max": "$$c.version"}}}}},
 {"$set": 
   {"docs": 
     {"$filter": 
       {"input": "$docs",
        "cond": 
         {"$or": 
           [{"$and": 
               [{"$gt": ["$$this.version", "$max-complete"]},
                 {"$eq": ["$$this.status", "incomplete"]}]},
             {"$and": 
               [{"$eq": ["$$this.version", "$max-complete"]},
                 {"$eq": ["$$this.status", "complete"]}]}]}}}}},
 {"$unwind": "$docs"},
 {"$replaceRoot": {"newRoot": "$docs"}}])