'How to check if array that inside an object contains element mongoDB

Hi i have this document :

{
    "_id" : ObjectId("62792b4a0c9c5a00b6a8e17b"),
    "username" : "user_1",
    "words" : [ 
        {
            "word" : "RATIONAL",
            "subwords" : [ 
                "RAT", 
                "TAN"
            ]
        }, 
        {
            "word" : "YOUNGER",
            "subwords" : [ 
                "YOU", 
                "YOUR"
            ]
        }
    ]
}

I want to find a document that has a specific word for example "RATIONAL" and his subwords array contains an element.

for example i want to check if there is a document that has: username:"user_1 in his words array he contains the word:"RATIONAL" and his subwords array contains the word "RAT"

something like that:

db.users.find({username:"user_1","words":{word:"RATIONAL",subword:"RAT"}}).pretty();

thanks everyone :)



Solution 1:[1]

This should work for you:

db.users.find({"username": "user_1", "words.word": "RATIONAL", "words.subwords": "RAT"})

You also could use the The $elemMatch operator:

db.users.find({"username": "user_1",  "words": { "$elemMatch": { "word": "RATIONAL", "subwords": "RAT" } }})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1