How to modify data inside array?

Hi there!

I have an entry on a collection that goes as:

{ brand: "mine",
_people: { _email: something@gmail.com, 
           quantity: NR,  
           dateadded: thedate },
last_update: currentDate,
... }

And I’m trying to use a $set on the quantity, and I want to modify the quantity, how do I do that?

I tried updateOne({"_people._email": email }, {$set { … } ) but it doesn’t work, how can I do this?

I’m using a simple check on db for value, and update the value to that value plus amount on post method…

Heeelp x)

Hi @Zoo_Zaa,
above there is an example of how can you update the quantity entry:

> db.test.find().pretty()
{
        "_id" : ObjectId("63bc1831963835bf5abafedc"),
        "brand" : "mine",
        "_people" : {
                "_email" : "something@gmail.com",
                "quantity" : "NR",
                "dateadded" : "thedate"
        },
        "last_update" : "currentDate"
}
> db.test.update({"_people.quantity":{$eq:"NR"}},{$set:{"_people.quantity":"new value"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test.find().pretty()
{
        "_id" : ObjectId("63bc1831963835bf5abafedc"),
        "brand" : "mine",
        "_people" : {
                "_email" : "something@gmail.com",
                "quantity" : "new value",
                "dateadded" : "thedate"
        },
        "last_update" : "currentDate"
}

The reference for a better understand of how to use the update operator is here:
db.collection.update() — MongoDB Manual

i hope this answer is useful for you!

Best regards

Very useful, what does the $eq stand for? Asking cause the NR might be ever changing, must I add a query to check that NR before updating it?

(Thank yooou!)

Hi @Zoo_Zaa ,
$eq stands for “equals” and yes, you need to define the right query for your use case.

Regards

1 Like

Thank you very much for your help, highly appreciated!

By the way, what do you recomend to get the value of that $eq on an entry from an array? The find one brings back the whole document, not just the entry nr i from the array, I’m not sure what to use for defining the variable used in $eq…

can I use the $eq and use the field instead of the value?

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.