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
MongoDB query to display all the values excluding the id?
For this, use the $project. The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields
Let us first create a collection with documents −
> db.demo226.insertOne({"Name":"Chris","Age":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3f9be803d395bdc2134738")
}
> db.demo226.insertOne({"Name":"Bob","Age":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3f9bf003d395bdc2134739")
}
> db.demo226.insertOne({"Name":"David","Age":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3f9bf803d395bdc213473a")
}
Display all documents from a collection with the help of find() method −
> db.demo226.find();
This will produce the following output −
{ "_id" : ObjectId("5e3f9be803d395bdc2134738"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e3f9bf003d395bdc2134739"), "Name" : "Bob", "Age" : 20 }
{ "_id" : ObjectId("5e3f9bf803d395bdc213473a"), "Name" : "David", "Age" : 22 }
Following is the query to display all the values excluding id −
> db.demo226.aggregate(
... {$project:
... {
... _id: false,
..." StudentFirstName":"$Name",
... "StudentAge":"$Age"
... }
... }
...);
This will produce the following output −
{ "StudentFirstName" : "Chris", "StudentAge" : 21 }
{ "StudentFirstName" : "Bob", "StudentAge" : 20 }
{ "StudentFirstName" : "David", "StudentAge" : 22 }Advertisements