Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to return only embedded document?
It is not possible to return only embedded document. However, it will return all the documents from a collection. Let us first implement the following query to create a collection with documents
>db.queryToEmbeddedDocument.insertOne({"UserName":"Larry","PostDetails":[{"UserMessage":"Hello","UserLikes":8},{"UserMessage":"Hi","UserLikes":6},{"UserMessage":"Good Morning","UserLikes":12},{"UserMessage":"Awesome","UserLikes":4}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c988a9f330fd0aa0d2fe4bd")
}
Following is the query to display all documents from a collection with the help of find() method
> db.queryToEmbeddedDocument.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5c988a9f330fd0aa0d2fe4bd"),
"UserName" : "Larry",
"PostDetails" : [
{
"UserMessage" : "Hello",
"UserLikes" : 8
},
{
"UserMessage" : "Hi",
"UserLikes" : 6
},
{
"UserMessage" : "Good Morning",
"UserLikes" : 12
},
{
"UserMessage" : "Awesome",
"UserLikes" : 4
}
]
}
Following is the query to return all the documents from a collection
> db.queryToEmbeddedDocument.find({"PostDetails.UserLikes": {$gte: 8}},{PostDetails:1}).pretty();
This will produce the following output
{
"_id" : ObjectId("5c988a9f330fd0aa0d2fe4bd"),
"PostDetails" : [
{
"UserMessage" : "Hello",
"UserLikes" : 8
},
{
"UserMessage" : "Hi",
"UserLikes" : 6
},
{
"UserMessage" : "Good Morning",
"UserLikes" : 12
},
{
"UserMessage" : "Awesome",
"UserLikes" : 4
}
]
}
Look at the above sample output, we are getting all the documents while we want only those documents in which “UserLikes” are greater than or equal to 8.
Advertisements