We know that "IN" operator is very useful in SQL , It allows to specify various values in where clause.
SELECT Firstname,Lastname FROM Users
WHERE City IN ('Tbilisi','London');
This is very simple and clear in SQL , this would return all first name and last name from Users Table where the City column is either Tbilisi or London.
But how to run similar query in Mongodb ? I hope you have already touch mongo :)
First Let me introduce structure of the my test mongodb collection "Users".
You can download and import test data from here
You can download and import test data from here
One document entry will look like this.
{
"_id" : ObjectId("51f80e4ba44433577cb1bdbc"),
"Firstname" : "Leqso",
"Lastname" : "Zazikashvili",
"City" : "Tbilisi",
"Languages" : [
"English",
"Spanish",
"German"
]
}
Now lets write query to fetch all entries from mongodb where the City is Tbilisi or London
db.users.find(
{ City: {$in:["Tbilisi","London"]} }
)
As we can see $in operator selects the entries where the field value equals any value in the specified array. We can also get this entries from subarray.This will fetch all entries where subarray of languages contains "Chinese" or "Spanish"
db.users.find(
{ Languages: {$in:["Chinese","Spanish"]} }
)
No comments:
Post a Comment