Update array element in mongo

浪子不回头ぞ 提交于 2021-02-17 06:11:25

问题


I want to update an array that I have in a mongo doc. The structure of which looks something like:

{
  _id: id,
  myArray: [
    {key1: val, key2: val, key3: val}, 
    {key1: val, key2: val, key3: val}, 
    {key1: val, key2: val, key3: val}
  ]
}

I need to be able to do something like the SQL equivalent of update WHERE. Namely, get this particular document in the collection by searching with id (which you can do trivially with MyDoc.update({_id: id}...);) and then locate the specific object in the array based on a key value pair, and then update the value of a different key in that same object.


回答1:


When mongodb queries an array field it provides a positional operator $ which you can use to access a specific element in that array. You can use an elemMatch operator to search into the fields within an array of objects.

Example:

db.myCollection.find({
   _id: ObjectId("53b1a44350f148976b0b6044"),
   myArray: {
      $elemMatch: {key1: 'somevalue'}
   }
}, {
   $set:{
      'myArray.$.key2': 'someOtherValue'
   }
});

See: http://docs.mongodb.org/manual/reference/operator/update/positional/



来源:https://stackoverflow.com/questions/28980529/update-array-element-in-mongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!