Search code examples
mongodbarr

How to select from field name from nested arrays in mongodb?


I have a document with nested arrays and I can't work out how to select the from the a field.

I'd like to select all documents where "components" has a "mast".

I've tried.

db.sites.find({"components": "mast" } ).pretty();

db.sites.find({"components.$": "mast" } ).pretty();

db.sites.find({"components.$.$": "mast" } ).pretty();

db.sites.find({"components.$.$.mast": {$exists: true} } ).pretty();

db.sites.find({"components.$.mast": {$exists: true} } ).pretty();

db.sites.find({"components.mast": {$exists: true} } ).pretty();

and a bunch of other failed attempts.

{
    "_id" : ObjectId("23456yujbvfdfg"),
    "d": 1234567,
    "components" : [
        [
            "mast",
            {
                "foo":"bar"
            }
        ],
        [
            "commsbox",
            {
                "BLARN": "bAAA"
            }
        ]
    ]
}

My attempts are only returning blank results.


Solution

  • If you are maintaining components as array then you query should look like

    db.test.find({ "components": { $elemMatch:  { $elemMatch:  {$eq:"mast"}  } }})
    

    I have posted the solution based on the schema you have shared but i am certain that schema needs to be changed