Iterate over objects in an object

I need to be able to iterate over each object in “2016” to get the “desc”. I tried to use “$” but, this did not work.

"procedures": [{
    "2016": {
        "0": {
            "code": "XXXX",
            "desc": "hello desc",
            "my_data": [{
                "code": "99202",
                "count_of_services": 21,
                "spend": 754.279999998
            }, {
                "code": "99205",
                "count_of_services": 11,
                "spend": 1234.8600000000001
            }]
        },
        "1": {
            "code": "XXXX",
            "desc": "hello desc",
            "my_data": [{
                "code": "99202",
                "count_of_services": 21,
                "spend": 754.279999998
            }, {
                "code": "99205",
                "count_of_services": 11,
                "spend": 1234.8600000000001
            }]
        },
        "2": {
            "code": "XXXX",
            "desc": "hello desc",
            "my_data": [{
                "code": "99202",
                "count_of_services": 21,
                "spend": 754.279999998
            }]
        }
    }
}]

What you want to to do is not clear.

Post the expected result from the input document you shown.

Post exact code that you tried. What exactly happen?

I want to loop each {} of 2016 and be able to reach each “desc”.

I tried db.people.find({ "procedures.2016.$.desc": { $regex: /Procedure/i}}) but, nothing returned.

Then I used db.people.find({ "procedures.2016.0.desc": { $regex: /Procedure/i}}) This returned what I want but, only at the top ‘0’ level. I need it to got through all levels and check for ‘Procedure’. I also do not know how many levels there are in each.

Use

{"procedures.2016.desc": { $regex: /Procedure/i}}

rather than

So, I tried that and nothing showed. So, I used a count on the original and this code. This code produced 0.

db.people.find({"procedures.2016.desc": { $regex: /Procedure/i}}).count()

0

I have just notice that procedures.2016 IS NOT an array. Thus you cannot use array operations. I should have see that before as your title was clear. 8-(

You will need to update with a pipeline using https://docs.mongodb.com/manual/reference/operator/aggregation/objectToArray/

I keep trying different variations but all keep coming back as null. This is how I target the objects to convert to array right?

$objectToArray: "$procedures.2016"

See https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/

But I think that what complicates your use-case is that you are using number as field names.

You might consider using Building with Patterns: The Attribute Pattern | MongoDB Blog

Having dynamic keys (2016 looks like a year and as such is dynamic) makes indexing and other things very difficult.