JGCW
JGCW

Reputation: 1529

MongoDB - PHP modifying array's object values

I have a field which stores an array of objects. I want to modify the object's "status" value depending on the "id" value the object possesses.

"authors" : [ 
        {
            "id" : "18",
            "first_name" : "Buddhika",
            "last_name" : "Chathuranga",
            "$$hashKey" : "object:35",
            "status" : NumberLong(0)
        }, 
        {
            "id" : "3", // search for this number
            "first_name" : "Pasindu",
            "last_name" : "Priyanath",
            "$$hashKey" : "object:43",
            "status" : NumberLong(0) // modify this to 1
        }
    ],

Upvotes: 0

Views: 294

Answers (2)

Sandesh
Sandesh

Reputation: 1044

We can leverage positional update in MongoDB to update values inside array.

Mongo Positional Update

Please find script below.

db.authors.update(
{"authors.id": "3"},
{ $set: { "authors.$.status" : NumberLong(1) }} 
)

Upvotes: 2

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26278

Update in Mongo DB php:

db.collection.update( criteria, objNew, upsert, multi );

Detail Explanation

Upvotes: 0

Related Questions