Home > Back-end >  How to check if array that inside an object contains element mongoDB
How to check if array that inside an object contains element mongoDB

Time:05-10

Hi i have this document :

[1]: https://i.stack.imgur.com/DGGLo.png

Im want to find a document that has a specific "word" for example "RATIONAL" and his "subword" 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 sub word array contains the word "RAT"

something like that:

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

thanks everyone :)

CodePudding user response:

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.getCollection('configs').find({"username": "user_1",  "words": { "$elemMatch": { "word": "RATIONAL", "subwords": "RAT" } }})
  • Related