Search code examples
arraysmongodbloopback

Loopback Update property Array of Object


I'm use loopback and mongodb. Right now I have a Model and one of its property type is array of object. The document in mongo will look like this

{
  "id": "123123213",
  "name": "Some Name",
  "colors": [{
    "colorId": "1"
    "colorName: "Red"
  }, {
    "colorId": "2",
    "colorName: "Blue"
  }]
}

Now i have a requirements to querying update and delete specific object in colors array. Let say i need to update the colorName only in colorId 2 to Green. And delete the Color object which the colorId is 2.

How to achieve this in loopback? Please advise ! Thank you.


Solution

  • In mongo CLI, you can use $ (positional) to update matching element from an embedded array document

    update

    > db.colors.update({"colors.colorId" :"2"}, {$set : {"colors.$.colorName" : "Green"}})
    

    use $pull to delete

    > db.colors.update({}, {$pull : {"colors" : {"colorId" : "2"}}})