- 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
How to prevent MongoDB from returning the object ID while finding a document?
To prevent MongoDB from returning the Object ID while finding a document, you need to set _id to 0. Let us first create a collection with documents
> db.preventObjectIdDemo.insertOne( ... { ... ... "StudentName" : "Chris", ... "StudentDetails" : [ ... { ... "StudentTotalScore" : 540, ... "StudentCountryName" : "US" ... }, ... { ... "StudentTotalScore" : 489, ... "StudentCountryName" : "UK" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ca20a9c66324ffac2a7dc63") }
Following is the query to display all documents from a collection with the help of find() method
> db.preventObjectIdDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5ca20a9c66324ffac2a7dc63"), "StudentName" : "Chris", "StudentDetails" : [ { "StudentTotalScore" : 540, "StudentCountryName" : "US" }, { "StudentTotalScore" : 489, "StudentCountryName" : "UK" } ] }
Following is the query to prevent MongoDB from returning the Object ID when finding a document
> db.preventObjectIdDemo.find({ _id: ObjectId("5ca20a9c66324ffac2a7dc63")}, {StudentDetails: { $slice: [0, 1] } ,'_id': 0} ).pretty();
The following is the output where ObjectID isn’t visible
{ "StudentName" : "Chris", "StudentDetails" : [ { "StudentTotalScore" : 540, "StudentCountryName" : "US" } ] }
Advertisements