- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.
- Related Articles
- Return specific MongoDB embedded document
- MongoDB query for fields in embedded document?
- Filter query on array of embedded document with MongoDB?
- MongoDB - Query embedded documents?
- Implement MongoDB $push in embedded document array?
- How to get embedded data in a MongoDB document?
- MongoDB query to update nested document
- Increment a field in MongoDB document which is embedded?
- How to find a certain element in the MongoDB embedded document?
- MongoDB query select and display only a specific field from the document?
- MongoDB query to remove a specific document
- MongoDB query to get last inserted document?
- MongoDB query to remove subdocument from document?
- MongoDB query to update the nested document?
- MongoDB - How to check for equality in collection and in embedded document?

Advertisements