Dweep Panchal
Dweep Panchal

Reputation: 63

How to update specific data in array in MongoDB?

{
  "_id":{"$oid":"5f5287db8c4dbe22383eca58"},
  "__v":0,
  "createdAt":{"$date":"2020-09-12T11:35:45.965Z"},
  "data":["Buy RAM","Money buys freedom"],
  "updatedAt":{"$date":"2020-09-12T11:38:10.637Z"}
}

I want to update the first element in this data array field as Buy SSD.

How can I do it using NodeJS?

Upvotes: 1

Views: 70

Answers (4)

Dyn4sty
Dyn4sty

Reputation: 176

UpdateOne -> Updates a single Document:

db.collection.updateOne(filter, update, options)

You will probably gonna filter using the _id field, and use $set to update the specific field.

Use the dot-notation to access and set fields deep inside objects, without affecting the other properties of those objects.

you want to update the 1st array entry in "data", and array keys are 0 indexed - that's the key 0.

so the query will look something like that:

    db.collection.update(
       { _id: { "$oid": "56476e04e5f19d86ece5b81d"}, // probb ObjectId Instance
       { $set:
          {
            "data.0": "Buy SSD" // Using dot-notation
          }
       }
    )

for more advanced use, you can use the MongoDB's positional operator $ without explicitly specifying the position of the element in the array. The positional operator allows you to use a condition like this:

{"Order.name": "test"}

and then reference the found array entry like so:

{"Order.$  // <- the dollar represents the first matching array key index

Example:

/* DATA
{
    "_id" : "43434", 
    "Order" : [
        {"name" : "test", "items" : ["", "new_value", "" ]},
        {"name" : "test2", "items" : ["", "", "" ]}
    ]
}
 */ 

db.collection.update(
   { _id: "43434", "Order.name": "test2"},
   { $set:
      {
        "Order.$.items.1": "new_value2" // positional operator & dot-notation.
      }
   }
)
>>> db.collection.find()  
{
    "_id" : "43434", 
    "Order" : [
        {"name" : "test", "items" : ["", "new_value", "" ]},
        {"name" : "test2", "items" : ["", "new_value2", "" ]}
    ]
}

Upvotes: 0

birbhouse
birbhouse

Reputation: 158

You can use str.replace()

var product = 
    [{
      "_id":{"$oid":"5f5287db8c4dbe22383eca58"},
      "__v":"0",
      "createdAt":{"$date":"2020-09-12T11:35:45.965Z"},
      "data":["Buy RAM","Money buys freedom"],
      "updatedAt":{"$date":"2020-09-12T11:38:10.637Z"}
    }]
var new_product = JSON.stringify(product).replace("Buy RAM", "Something");
console.log(new_product);

Upvotes: 0

Gaurav Sharma
Gaurav Sharma

Reputation: 633

You can use filtered positional operator

db.collectionName.updateOne(
{
    "_id.$oid": "5f5287db8c4dbe22383eca58"
}, 
{
    $set: {
        "data.$[element]": "Buy SSD"
    }
},
{
    { arrayFilters: [ { element: "Buy Ram" } ] }
})

Caution: It will update all array element matching the text. In this case, "Buy Ram"

Upvotes: 0

rantao
rantao

Reputation: 1832

db.collection.findOneAndUpdate({
    "_id.$oid": "5f5287db8c4dbe22383eca58",
    data: "Buy RAM"
}, {
    $set: {
        "data.$" "Buy SSD"
    }
})

This query updates the first element in the data array inside the document that matches "_id.$oid": "5f5287db8c4dbe22383eca58", using $ positional identifier and sets it to the new value.

For more Array Update Operators in mongodb, here is a reference: mongodb manual

Upvotes: 1

Related Questions