- 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 add a field with static value to MongoDB find query?
You can use $literal operator along with aggregate framework. Let us first create a collection with documents −
> db.fieldWithStaticValue.insertOne({"Name":"Larry","Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6554c7924bb85b3f48948") } > db.fieldWithStaticValue.insertOne({"Name":"Chris","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cd655567924bb85b3f48949") } > db.fieldWithStaticValue.insertOne({"Name":"David","Age":26}); { "acknowledged" : true, "insertedId" : ObjectId("5cd655607924bb85b3f4894a") }
Following is the query to display all documents from a collection with the help of find() method −
> db.fieldWithStaticValue.find();
This will produce the following output −
{ "_id" : ObjectId("5cd6554c7924bb85b3f48948"), "Name" : "Larry", "Age" : 24 } { "_id" : ObjectId("5cd655567924bb85b3f48949"), "Name" : "Chris", "Age" : 23 } { "_id" : ObjectId("5cd655607924bb85b3f4894a"), "Name" : "David", "Age" : 26 }
Following is the query to add field with static value to MongoDB using $literal −
> db.fieldWithStaticValue.aggregate( [ { $project: { Name: 1,Age:1, "StaticValue": { $literal: 100 } } } ]);
This will produce the following output −
{ "_id" : ObjectId("5cd6554c7924bb85b3f48948"), "Name" : "Larry", "Age" : 24, "StaticValue" : 100 } { "_id" : ObjectId("5cd655567924bb85b3f48949"), "Name" : "Chris", "Age" : 23, "StaticValue" : 100 } { "_id" : ObjectId("5cd655607924bb85b3f4894a"), "Name" : "David", "Age" : 26, "StaticValue" : 100 }
Advertisements
To Continue Learning Please Login
Login with Google