11

So pretty new and absolutely uneducated on MongoDB.

Having this JSON structure:

{
"id": "123456",
"makes": {
    "abc": {
        "att1": 4,
        "att2": "fffff",
        "att3": 46
        },
    "fgh": {
        "att1": 8,
        "att2": "ggggg",
        "att3": 6
    },
    "rty": {
        "att1": 3,
        "att2": "hhhh",
        "att3": 4
        },
    "iop": {
        "att1": 4,
        "att2": "llll",
        "att3": 3
        }
}

}

how can I query the DB for "fgh" make? I tried:

db.<myCollection>.find({"makes":"fgh"})

but that doesn't work. It works fine if I write:

db.<myCollection>.find({"makes.fgh.att1":8})

thank you in advance!

1 Answer 1

26

When you try to query for makes.fgh, you don't do a query on the content, but on the structure, as "fgh" is not a value but a sub-document.

You can achieve this with a $exists search:

db.myCollection.find( { "makes.fgh" : { $exists : true } })

See https://docs.mongodb.com/manual/reference/operator/query/exists/ for reference.

To integrate @chridam's helpful comment:

If you are only interested in that sub-document, you can also add a projection to the find:

db.myCollection.find({ "makes.fgh" : { $exists : true }}, { "makes.fgh" : 1 })

Have a look at https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find for details.

Sign up to request clarification or add additional context in comments.

6 Comments

Also worth mentioning the projection of the subdocument after the query db.<myCollection>.find({ "makes.fgh": { "$exists": true } }, { "makes.fgh": 1 })
Yes, right. Edited the answer to include this fact.
It's starting to make more sense now, thanks both for your help!
A gotcha for the node driver - projection param should have "projection" as a key, e.g. db.<myCollection>.find({ "makes.fgh": { "$exists": true } }, { projection: { "makes.fgh": 1 }})
Would it be possible to somehow pattern match? eg: fg*?
|

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.