

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 an array field value with MongoDB?
You can use positional operator $. Let us first create a collection with documents −
> db.replaceAnArrayFieldValueDemo.insertOne({"StudentTechnicalSubjects":["MySQL","SQL Server","PL/SQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cea41e0ef71edecf6a1f68f") }
Following is the query to display all documents from a collection with the help of find() method −
> db.replaceAnArrayFieldValueDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cea41e0ef71edecf6a1f68f"), "StudentTechnicalSubjects" : [ "MySQL", "SQL Server", "PL/SQL" ] }
Following is the query to replace an array field value. Here, we are updating “SQL Server” with “MongoDB” −
> db.replaceAnArrayFieldValueDemo.update( {"StudentTechnicalSubjects":"SQL Server"}, { $set: { 'StudentTechnicalSubjects.$': "MongoDB" }} ); WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
Let us check the document once again −
> db.replaceAnArrayFieldValueDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cea41e0ef71edecf6a1f68f"), "StudentTechnicalSubjects" : [ "MySQL", "MongoDB", "PL/SQL" ] }
- Related Questions & Answers
- MongoDB query to replace value in an array?
- Make MongoDB replace single array value with string?
- Query a nested field within an array with MongoDB
- MongoDB query to replace value with aggregation?
- How to project specific elements in an array field with MongoDB?
- How to exclude array type field value in MongoDB?
- Increment value of an array element with array object in MongoDB
- Find and replace NumberLong type field in MongoDB?
- Update MongoDB field using value of another field?
- MongoDB query to update array with another field?
- Set MongoDB compound index with a fixed value field
- MongoDB aggregation to fetch documents with specific field value?
- Replace value with a string literal during MongoDB aggregation operation
- Delete all elements in an array field in MongoDB?
- Reverse array field in MongoDB?
Advertisements