首页 > 解决方案 > 将条件推入数组

问题描述

我们只需要push/addtoset 文件中的key ne []
怎么实现

{
    "_id" : ObjectId("xxxxxx"),
    "shop" : "REQ4",
    "bolt" : "5647",
    "nut" : "1111",
}
{
    "_id" : ObjectId("xxxxxx"),
    "shop" : "REQ4",
    "bolt" : "2314",
    "nut":[]
}
Aggregates.group("$shop", Accumulators.addToSet("bolt", "$bolt"),Accumulators.addToSet("nut", "nut"))//only if nut ne []

预期输出:

{ "_id" : "REQ4", "bolt" : ["5647", "2314"], "nut" : ["1111"]

标签: mongodbaggregation-frameworkmongodb-3.6.4

解决方案


你可以先$push然后可以用$filter来排除[]

db.collection.aggregate([
  { "$group": {
    "_id": "$shop",
    "bolt": { "$push": "$bolt" },
    "nut": { "$push": "$nut" }
  }},
  { "$addFields": {
    "nut": {
      "$filter": {
        "input": "$nut",
        "cond": { "$ne": ["$$this", []] }
      }
    }
  }}
])

推荐阅读