Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }
  }
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading