- 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 limit subdocuments having the given fields of the 'projection'
For this, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo285.insertOne( ... {... details : [ ... { ... Name : "Chris" ... }, ... { ... Name2: "Bob" ... }, ... { ... Name: "Mike" ... } ... ] ... } ...) { "acknowledged" : true, "insertedId" : ObjectId("5e4abffef49383b52759cbb9") }
Display all documents from a collection with the help of find() method −
> db.demo285.find();
This will produce the following output −
{ "_id" : ObjectId("5e4abffef49383b52759cbb9"), "details" : [ { "Name" : "Chris" }, { "Name2" : "Bob" }, { "Name" : "Mike" } ] }
Following is the query to limit subdocuments having the given fields of the `projection` −
> db.demo285.aggregate( ... [ ... { $match: ... {'details.Name' : ... { $exists: 1 } ... } ... }, ... { $unwind: "$details" }, ... { $match: ... {'details.Name' : ... { $exists: 1 } ... } ... }, ... { $project: { Name: "$details.Name", _id: 0 } } ... ])
This will produce the following output −
{ "Name" : "Chris" } { "Name" : "Mike" }
- Related Articles
- MongoDB Limit fields and slice projection together?
- MongoDB query to sort subdocuments
- MongoDB query with an 'or' condition?
- Query array of subdocuments in MongoDB
- MongoDB query to 'sort' and display a specific number of values
- What is the BSON query for the command 'show dbs' (list of databases) in MongoDB?
- Query Array for 'true' value at index n in MongoDB?
- MySQL query to select ENUM('M', 'F') as 'Male' or 'Female'?
- Opposite of $addToSet to '$removeFromSet' in MongoDB?
- MongoDB query to check the existence of multiple fields
- MongoDB query to limit the returning values of a field?
- MongoDB Query to select records having a given key?
- MongoDB query to insert but limit the total records
- MongoDB query to exclude both the fields with FALSE
- MongoDB query to sum specific fields

Advertisements