Home > Mobile >  mongodb get all values for a specific field in an inner array
mongodb get all values for a specific field in an inner array

Time:12-16

I am new to mongodb and I am struggling to understand something that I think should be pretty simple, maybe you can point me out in the right direction!

Lets say I have the following single document in a collection:

{
    "id": "1234",
    "name": "test",
    "elements": [
        {
            "name": "element1",
            "type": "exaple"
        },
        {
            "name": "element2",
            "type": "important"
        },
        {
            "name": "element3",
            "type": "exaple"
        },
        {
            "name": "element4",
            "type": "imporant"
        },
        {
            "name": "element5",
            "type": "exaple"
        }
    ]
}

And I want to get the name of all the "elements" that are important for this document.

An example of doing the same using JQ:

cat test.json | jq '.elements[] | select(.type=="important").name'
"element2"
"element4"

I imagine I need to use some sort of aggregation but I am not being able to do this simple thing, any suggestion?

CodePudding user response:

You can use an aggregation query like this:

  • First use $filter to get only values you want (i.e. elements with imporant type.
  • And then output only the name using $project.
db.collection.aggregate([
  {
    "$set": {
      "elements": {
        "$filter": {
          "input": "$elements",
          "cond": {
            "$eq": [
              "$$this.type",
              "important"
            ]
          }
        }
      }
    }
  },
  {
    "$project": {
      "result": "$elements.name"
    }
  }
])

Example here

CodePudding user response:

You can do this with a simple $cond in a $reduce

db.collection.aggregate([
  {
    "$project": {
      result: {
        "$reduce": {
          "input": "$elements",
          "initialValue": [],
          "in": {
            "$cond": {
              "if": {
                $eq: [
                  "important",
                  "$$this.type"
                ]
              },
              "then": {
                $setUnion: [
                  "$$value",
                  [
                    "$$this.name"
                  ]
                ]
              },
              "else": "$$value"
            }
          }
        }
      }
    }
  }
])

Mongo Playground

  • Related