Click the link: "MongoDB - Query an Array"
In this MongoDB tutorial we will learn to query arrays.
Login to your MongoDB server and insert the following documents.
For this tutorial I will insert the following documents in the posts collection.
> db.posts.insertMany([
{
"title": "This is my first post!",
"tags": ["awesome", "post", "blog"]
},
{
"title": "Dinner time :)",
"tags": ["food", "dinner", "fun"]
},
{
"title": "Birthday Treat",
"tags": ["fun", "food", "birthday", "treat", "party"]
}
]);
Match exact array
In the following example we are going to fetch documents having exactly 3 elements in the array and values are
awesome
, post
and blog
in that order.> db.posts.find({
"tags": ["awesome", "post", "blog"]
}).pretty();
{
"_id" : ObjectId("5d1b43d9085e37060f4c36b5"),
"title" : "This is my first post!",
"tags" : [
"awesome",
"post",
"blog"
]
}
Note! If we change the positions of the array elements in the above query then we will not get the same result.
Query an array for an element
In the following example we are going to fetch all the documents having an array field
tags
that contains food
as one of the element in the array.> db.posts.find({ "tags": "food" }).pretty();
{
"_id" : ObjectId("5d1b43d9085e37060f4c36b6"),
"title" : "Dinner time :)",
"tags" : [
"food",
"dinner",
"fun"
]
}
{
"_id" : ObjectId("5d1b43d9085e37060f4c36b7"),
"title" : "Birthday Treat",
"tags" : [
"fun",
"food",
"birthday",
"treat",
"party"
]
}
Read more...
No comments:
Post a Comment