ICARUS
ICARUS

Reputation: 57

How can i update record on an embedded document in a mongoDB collection?

I have a mongoDB "ratings" collection which contains the below data

/* 1 */
{
  "_id": ObjectId("5f1e13936d702dc8b1aa47c8"),
  "ratings": [{
      "music": "PN1",
      "rating": "23"
    },
    {
      "music": "PN2",
      "rating": "24"
    }
  ],
  "email": "[email protected]",
  "username": "test1"
}

/* 2 */
{
  "_id": ObjectId("5f1e13f46d702dc8b1aa47c9"),
  "ratings": [{
      "music": "PN3",
      "rating": "45"
    },
    {
      "music": "PN4",
      "rating": "65"
    }
  ],
  "email": "[email protected]",
  "username": "test2"
}

I want to modify the PN1 rating for username "test1" and i execute the below code

db.getCollection('ratings').update(
    // query 
    {
      "_id": ObjectId("5f1e13936d702dc8b1aa47c8"),
      "email": "[email protected]"
    },

    // update 
    {
      "ratings.rating": "8"
    },

    // options 
    {
      "multi": false,
      "upsert": false
    );

The code works but instead of modifying just the PN1 rating for test1 user, the entire ratings list for that user was replaced the update. How can i fix this? I only want to modify the PN1 rating for the test1 user

Upvotes: 0

Views: 47

Answers (1)

Montgomery Watts
Montgomery Watts

Reputation: 4034

First you'll need to specify which element of the array you want to update, e.g. one that has a music value of PN1. You can do this by adding a field to the query that matches against the ratings.music field like so:

{
  "_id": ObjectId("5f1e13936d702dc8b1aa47c8"),
  "email": "[email protected]",
  "ratings.music": "PN1"
}

Now that you matched the document you want to update, you need to tell MongoDB how to update the document. An update document that changes the rating might look like this:

{
  $set:
        {
          "ratings.$.rating": 8
        }
}

This works by using the $ positional operator, which will update the first element in the ratings array that has a music field equal to PN1.

Upvotes: 1

Related Questions