Skyline
Skyline

Reputation: 145

In MongoDB, how do I find and update a particular array element?

Suppose I have the following MongoDB collection, and I'd like to find all documents whose ratings.by is ijk and update its rating to 6.

In other words, update { by: "ijk", rating: 4 } to { by: "ijk", rating: 6 }. The problem is that I don't know the index of such array element.

{
  _id: 1,
  item: "TBD",
  stock: 0,
  info: { publisher: "1111", pages: 430 },
  tags: [ "technology", "computer" ],
  ratings: [ { by: "ijk", rating: 4 }, { by: "lmn", rating: 5 } ],
  reorder: false
}

My Question: How should I write the db.collection.update() function? This is my unsuccessful attempt:

db.collection.update({
    ratings.by: {
        $elemMatch: {
            $eq: 'ijk'
        }
    }
}, {
    $set: {
        // don't know which index to set. How should I modify this line?
        ratings.rating: 6
    }
}, {
    multi: true
});

Upvotes: 0

Views: 45

Answers (1)

chridam
chridam

Reputation: 103305

Use the $ positional operator which identifies an element in an array to update without explicitly specifying the position of the element in the array:

db.collection.update(
    { "ratings.by": "ijk" }, 
    { "$set": { "ratings.$.rating": 6 }},
    { "multi": true }
);

Upvotes: 1

Related Questions