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
How to exclude _id without including other fields using the aggregation framework in MongoDB?
Let us first create a collection with documents −
> db.excludeIdDemo.insertOne({"StudentFirstName":"John","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd701a56d78f205348bc632")
}
> db.excludeIdDemo.insertOne({"StudentFirstName":"Robert","StudentAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd701af6d78f205348bc633")
}
> db.excludeIdDemo.insertOne({"StudentFirstName":"Chris","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd701b86d78f205348bc634")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.excludeIdDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd701a56d78f205348bc632"), "StudentFirstName" : "John", "StudentAge" : 21 }
{ "_id" : ObjectId("5cd701af6d78f205348bc633"), "StudentFirstName" : "Robert", "StudentAge" : 20 }
{ "_id" : ObjectId("5cd701b86d78f205348bc634"), "StudentFirstName" : "Chris", "StudentAge" : 24 }
Following is the query to exclude _id without including other fields using the aggregation framework −
> db.excludeIdDemo.aggregate(
{
$project :
{
_id : 0,
"StudentFirstName": 1
}
}
);
This will produce the following output −
{ "StudentFirstName" : "John" }
{ "StudentFirstName" : "Robert" }
{ "StudentFirstName" : "Chris" }Advertisements