简体   繁体   中英

How to query MongoDB to see if a field (string) matches an element in an array (of strings)?

I have an array of strings and I want to find all documents that have a field with the value that is contained in a an array.

For example, say I have the array kidsInTrouble = ["Jerry", "Tom", "Arnold"] ,

I want to search through my Students collection to find all the kids who's name field is either "Jerry" , "Tom" , or "Arnold" .

(Bonus points if a solution can be provided using Spring's Mongo Driver methods)

您的查询应如下所示:

db.students.find({"name": {$in:[$your_variable]})

You'd want to use the $in operator like this:

var kidsInTrouble = ["Jerry", "Tom", "Arnold"]
db.collection.find({name: {$in: kidsInTrouble}})

Check out this answer for an example using the $in operator from Java:

https://stackoverflow.com/a/37347298/6440033

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM