MongoDB find key on nested object KEY (JSON)

15,300

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.

Share:
15,300
Zenigata
Author by

Zenigata

Updated on July 23, 2022

Comments

  • Zenigata
    Zenigata over 1 year

    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!

  • chridam
    chridam over 7 years
    Also worth mentioning the projection of the subdocument after the query db.<myCollection>.find({ "makes.fgh": { "$exists": true } }, { "makes.fgh": 1 })
  • mtj
    mtj over 7 years
    Yes, right. Edited the answer to include this fact.
  • Zenigata
    Zenigata over 7 years
    It's starting to make more sense now, thanks both for your help!
  • danwild
    danwild over 5 years
    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 }})
  • openCivilisation
    openCivilisation almost 3 years
    Would it be possible to somehow pattern match? eg: fg*?
  • mtj
    mtj almost 3 years
    @openCivilisation No, I am not aware of such a feature.