How to query an array in MongoDB?
In this post you will learn how to query an array in a MongoDB collection. You will also learn how to filter a pattern in an array in a document in Mongo collection.
Let’s define our usertags collection which we will be used for querying.
{ "_id" : ObjectId("5ebbdf95f75976616169b25d"), "tags" : [ "Medium", "Blue", "Sports", "Animals" ], "userId" : "john", "roleId" : "admin"} { "_id" : ObjectId("5ebbe0fcf75976616169b349"), "tags" : [ "Small", "Maple", "Outdoor", "Soccer" ], "userId" : "anand", "roleId" : "superuser"}' { "_id" : ObjectId("5ebe7336f7597661616b46bc"), "tags" : [ "XL", "Red", "TV", "Web" ], "userId" : "krit", "roleId" : "Supervisor"}
In the above collection, tags is an array that stores tags related to a user.
Let’s say you want to find out user with tags Blue. You can define your query like..
> db.usertags.find{{tags: "Blue"}} { "_id" : ObjectId("5ebbdf95f75976616169b25d"), "tags" : [ "Medium", "Blue", "Sports", "Animals" ], "userId" : "john", "roleId" : "admin"}
You can search for multiple elements using the following format. But this query matches the exact array, the whole array.
> db.usertags.find{{tags: ["Blue","Red"]}}
There’s no exact match for [“Blue”,”Red”], hence zero matches.
> db.usertags.find{{tags: [ "Medium", "Blue", "Sports", "Animals" ]}} { "_id" : ObjectId("5ebbdf95f75976616169b25d"), "tags" : [ "Medium", "Blue", "Sports", "Animals" ], "userId" : "john", "roleId" : "admin"}
Yay, there a match for this long array!
You can query a regex pattern on an array using the following format.
> db.usertags.find({tags: /lue/}) { "_id" : ObjectId("5ebbdf95f75976616169b25d"), "tags" : [ "Medium", "Blue", "Sports", "Animals" ], "userId" : "john", "roleId" : "admin"}