Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB find key on nested object KEY (JSON)

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!

like image 590
Zenigata Avatar asked Aug 18 '16 12:08

Zenigata


Video Answer


1 Answers

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.

like image 167
mtj Avatar answered Nov 02 '22 12:11

mtj