1

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.

1
  • 1
    What if components was an array of objects? Your queries are expecting that. Seems like a data modelling error to me. Commented Feb 15, 2019 at 11:46

3 Answers 3

2

You can use $elemMatch

db.sites.find(
   { "components": { $elemMatch:  { $elemMatch:  {$eq:"mast"}  } }}
)
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I have changed the schema as I was too confusing.
1

this should work

db.sites.find({
    "components": {
            $elemMatch: {
                $elemMatch: { $in: ['mast'] }
            }
    } 
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.