db.Posts.insert({
PostBy: "Pankaj Choudhary",
Time:new Date(),
Title:"MonogoDB Day2",
Tags:[
"NoSQL",
"MonogoDB",
"Database",
"SQL"
],
Likes:3,
Comment: [
{
CommentBY : "Sanjeev",
Text: "Nice Show"
},{
CommentBY : "Rahul",
Text: "Nice Explain"
}
]
})
1. Query: Select the name of all the posts containing a “SQL” element in their Tags array.
db.Posts.find(
{ Tags:"NoSQL" },
{ Title:1, Tags: 1 }
)
//OUTPUT :
/* 1 */
{
"_id" : ObjectId("5f23ef77aad11f8bad80678b"),
"Title" : "MonogoDB Day2",
"Tags" : [
"NoSQL",
"MonogoDB",
"Database",
"SQL"
]
}
Query for Embedded Document
The following query will return the result for all documents that contain a comment array and the array contains an embedded document and the value of the “CommentBy” field of the embedded document is equal to “Rahul”.
We have various methods for the embedded document. We will explain each method.
Method 1: Using $elemMatch :
db.Posts.find(
{
Comment: {
$elemMatch: {CommentBY : "Rahul"}
}
}
)
Method 2: Using “.” Dot notation
Syntax: db.Collection_Name.find({“Field_Name.ED_FiledName” : Value } )
db.Posts.find({
"Comment.CommentBY" : "Sanjeev"
})
Method 3: Exact Match
This method will return a result when the query successfully matches the value of all fields of the embedded document.
db.Posts.find({
Comment: {CommentBY: "Sanjeev", Text:"Nice Show"}
})
If we neglect any single field or any value of the embedded document field doesn’t match the value of the query then MongoDB will not display any result. Let’s try to remove the “Text” field from the previous query and examine the result.
db.Posts.find({
Comment: {CommentBY: "Sanjeev", Text:"Nice Show"}
})
So it’s necessary that we provide the value of all fields in the exact matching method.
Conditional Operator for Field That contain Array
If a field contains an array and the select query contains multiple conditional operators then if a single element of an array meets the condition of all the conditional operators then MongoDB will return the entire array.
db.Posts.find({
Likes : {$gt:0, $lt:20}
})