- 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
Update MongoDB variable value with variable itself?
You cannot update a column value using itself. For this, you can use $set. Let us create a collection with documents −
> db.demo256.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a3e91627c0c63e7dba8b") } > db.demo256.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a3ea1627c0c63e7dba8c") } > db.demo256.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a3eb1627c0c63e7dba8d") }
Display all documents from a collection with the help of find() method −
> db.demo256.find();
This will produce the following output −
{ "_id" : ObjectId("5e47a3e91627c0c63e7dba8b"), "Name" : "Chris" } { "_id" : ObjectId("5e47a3ea1627c0c63e7dba8c"), "Name" : "Bob" } { "_id" : ObjectId("5e47a3eb1627c0c63e7dba8d"), "Name" : "David" }
Following is the query to update variable value with variable itself −
> db.demo256.update({}, {$set:{"Name":"Name" + " is a student"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo256.find();
This will produce the following output −
{ "_id" : ObjectId("5e47a5301627c0c63e7dba8e"), "Name" : "Name is a student" } { "_id" : ObjectId("5e47a5311627c0c63e7dba8f"), "Name" : "Bob" } { "_id" : ObjectId("5e47a5311627c0c63e7dba90"), "Name" : "David" }
Advertisements