Search code examples
python-3.xmongodbpymongoaggregation

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


I have collections like:

[
  {
    "_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
  }
]

if religion is south and tested is true then get all the values of fruits in list.

tried:

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

getting result as : [{"fruit": "orange"}, {"fruit": "apple"}]

but result should be like: {"fruit" : ["orange", "apple"]}


Solution

  • use $group, $addToSet and using$cond you don't need the $match stage

    test it at mongoPlayground

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