
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
Replace Single Array Value with String in MongoDB
To replace, use $set and positional($) operator. Let us create a collection with documents −
> db.demo564.insertOne({"StudentName":["Chris","David","Mike","Sam"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e90880a39cfeaaf0b97b576") }
Display all documents from a collection with the help of find() method −
> db.demo564.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e90880a39cfeaaf0b97b576"), "StudentName" : [ "Chris", "David", "Mike", "Sam" ] }
Following is the query to replace single array value with string −
> db.demo564.updateMany( ... { "StudentName": "David" }, ... { "$set": { "StudentName.$": "Carol Taylor" } } ... ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } >
Display all documents from a collection with the help of find() method −
> db.demo564.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e90880a39cfeaaf0b97b576"), "StudentName" : [ "Chris", "Carol Taylor", "Mike", "Sam" ] }
Advertisements