更新mongo中的数组元素 [英] Update array element in mongo

查看:84
本文介绍了更新mongo中的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新我在 mongo 文档中的一个数组.其结构类似于:

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}
  ]
}

我需要能够做一些类似于更新 WHERE 的 SQL 等价物.即,通过使用 id 搜索(您可以使用 MyDoc.update({_id: id}...); 轻松完成)在集合中获取此特定文档,然后在基于键值对的数组,然后更新同一对象中不同键的值.

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.

推荐答案

当 mongodb 查询数组字段时,它提供了一个位置运算符 $,您可以使用它来访问该数组中的特定元素.您可以使用 elemMatch 运算符来搜索对象数组中的字段.

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.

示例:

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

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

这篇关于更新mongo中的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆