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" ] }