mongodb 聚合:获取列表中特定字段的所有值

mongodb aggregation: get all values for the particular field in list

我collections喜欢:

[
  {
    "_id": "1",
    "religion": "south",
    "tested": true,
    "fruit": "orange",
    "created_at": 2211123333
  },
  {
    "_id": "2",
    "religion": "north",
    "tested": false,
    "fruit": "apple",
    "created_at": 223444433
  },
  {
    "_id": "3",
    "religion": "north",
    "tested": true,
    "fruit": "orange",
    "created_at": 234567876
  }
]

如果宗教是南方的并且经过测试是真的那么获取列表中所有水果的值。

尝试过:

pipeline = [{"$match": {"$and": [{"religion": "south"}, {"tested": true}]}}, {}{"$project": {"fruit": 1, "_id": 0}}]
db.collection.aggregate(pipeline).to_list(length=None)

得到的结果为:[{"fruit": "orange"}, {"fruit": "apple"}]

但结果应该是这样的:{"fruit" : ["orange", "apple"]}

使用 $group$addToSet 并使用 $cond 你不需要 $match 阶段

mongoPlayground

进行测试
[
  {
    "$group": {
      "_id": null,
      "fruit": {
        "$addToSet": {
          "$cond": [
            {
              "$and": [
                {
                  "$eq": [
                    "$religion",
                    "south"
                  ]
                },
                {
                  "$eq": [
                    "$tested",
                    true
                  ]
                }
              ]
            },
            "$fruit",
            "$$REMOVE"
          ]
        }
      }
    }
  },
  {
    "$project": {
      fruit: 1,
      _id: 0
    }
  }
]