1

I have following document structure stored in Mongodb. Please note "next" is an array.

{
  "id": 1,
  "pricing": [
    {
      "name": "name1",
      "value": "v1",
      "next": [
        {
          "name": "name2",
          "value": "v2",
          "next": [
            {
              "name": "name3",
              "value": "v3",
              "next": [
              ]
            }
          ]
        }
      ]
    }
  ]
}

How can I find the eg. name=name3 or any arbitrary value from it? Not knowing if it exists or not.

harryk
  • 123
  • 1
  • 10

1 Answers1

1

You can match the field pricing.next.next.name and the value name3 like this.

db.collection.find({
  "pricing.next.next.name": "name3"
})

So it will return the document that contains the value name3 inside the two arrays.

Mongo Playground example here

Your question is not explained too well, so, maybe you mean, how to get only the field name after querying by name. Note that you can use other field like value to query the document.

Then, you have to do this:

db.collection.find({
  "pricing.next.next.name": "name3",
  
},
{
  "pricing.next.next.name": 1
})

And mongo Playground example here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
J.F.
  • 13,927
  • 9
  • 27
  • 65
  • Hi, thx for the reply. But I wouldn't know if there is an object 3 level down. eg. The pricing next.next could be null – harryk Nov 03 '20 at 16:37
  • If ```pricing.next.next``` is null or not exists, then no document will be returned. Is this your doubt? – J.F. Nov 03 '20 at 16:40
  • I want to search name3 on the entire tree. Not knowing which level it will be or it exists or not – harryk Nov 03 '20 at 17:43
  • Then check this [question](https://stackoverflow.com/questions/19802502/mongodb-query-help-query-on-values-of-any-key-in-a-sub-object/19802670#19802670) – J.F. Nov 03 '20 at 18:10