1
{
  "_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?

4 Answers 4

1
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

Sign up to request clarification or add additional context in comments.

4 Comments

Is there any way to update specific data. For Eg. my array is data: ["Buy RAM", "Buy RAM", "Bake Bread"] and I want to update that 2nd "Buy RAM". Can I do it?
If you know the position of the element you can use the index value instead of $, so in this example it should be data.1 to specify the second element in the data array
And if I don't know that index then how can I do it?
You may find this StackOverflow question useful
0

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"

6 Comments

@DweepPanchal Do upvote, It helps us keep contributing to the community. Shouldn't this be your answer? because this answer can replace any matching array element not just the first array element.
I want only the first element to update. So the above answer matches my need so I upvoted that. Thank you for your help Gaurav. Have a nice day!
But you did not specify this in the question. This answer is a superset to another answer.
See Gaurav there is nothing to offend here. If StackOverflow allows me to upvote both answers I will do both. But your answers come 2nd I get the above answer before you and it satisfied my need so I upvoted that.
It is totally fine but you should have specified this condition in the question.
|
0

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.