Home > database >  How to check if a value is in a document's field (which is an array)
How to check if a value is in a document's field (which is an array)

Time:10-31

Say we have a collection users:

{
    "name" : "Doe",
    "books": ["b1", "b2"]
},
{
    "name" : "Jhon",
    "books": ["b1", "b3"]
}

I want to check if a book b3 is in this collection (doesn't matter which document/user). How can I achieve that?

CodePudding user response:

Following query will get you the user who had "b3" book:

users.find( { books: ["b3"] } )

for further study: https://docs.mongodb.com/manual/tutorial/query-arrays/

CodePudding user response:

db.collection.find({books:{$in:["b3"]}})
  • Related