- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Retrieving a Subset of Fields from MongoDB
To retried a subset of fields, use dot notation in find(). Let us create a collection with documents −
> db.demo307.insertOne({ ... "CleintId":101, ... "ClientDetails":{"ClientFirstName":"Chris","Age":34}, ... "ClientCountryName":"US" ...} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4eab88f8647eb59e56203c") } > db.demo307.insertOne({ ... "CleintId":102, ... "ClientDetails":{"ClientFirstName":"David","Age":31}, ... "ClientCountryName":"UK" ...} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4eab97f8647eb59e56203d") }
Display all documents from a collection with the help of find() method −
> db.demo307.find();
This will produce the following output −
{ "_id" : ObjectId("5e4eab88f8647eb59e56203c"), "CleintId" : 101, "ClientDetails" : { "ClientFirstName" : "Chris", "Age" : 34 }, "ClientCountryName" : "US" } { "_id" : ObjectId("5e4eab97f8647eb59e56203d"), "CleintId" : 102, "ClientDetails" : { "ClientFirstName" : "David", "Age" : 31 }, "ClientCountryName" : "UK" }
Following is the query to retrieve a subset of fields from MongoDB −
> db.demo307.find( {"ClientDetails.ClientFirstName":'David'}, {"ClientDetails.Age" : 0,"ClientCountryName":0,CleintId:0,_id:0});
This will produce the following output −
{ "ClientDetails" : { "ClientFirstName" : "David" } }
Advertisements