MongoDB 更新(将项目列表插入数组)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10383682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:38:19  来源:igfitidea点击:

MongoDB Update (Insert a List of Item to an Array)

arraysmongodbmongodb-query

提问by hamed hamed

I want to add several items to arrays of several rows in Mongo. How can I do this?

我想在 Mongo 中将几个项目添加到几行的数组中。我怎样才能做到这一点?

I want to start with this:

我想从这个开始:

{'x': 'h', arr: [1,2,3] }
{'x': 'h', arr: [1,3] }

and add the array [6,8], where the x is equal to 'h':

并添加数组 [6,8],其中 x 等于 'h':

{'x': 'h', arr: [1,2,3,6,8] }
{'x': 'h', arr: [1,6,8] }

回答by Adam Comerford

I think what you are looking for is the $pushAll operator. Take a look here:

我认为您正在寻找的是 $pushAll 运算符。看看这里:

http://docs.mongodb.org/manual/reference/operator/pushAll/#pushall

http://docs.mongodb.org/manual/reference/operator/pushAll/#pushall

回答by theJollySin

If you have a MongoDB collection named yourCollectionand a record with the name x, you would update the subarray with something like this:

如果您有一个名为 MongoDB 的集合yourCollection和一个名为的记录x,您将使用以下内容更新子数组:

db.test.update( {"name":"x"}, {"$pushAll" : {arr : [1, 2, 3]}} )

db.test.update( {"name":"x"}, {"$pushAll" : {arr : [1, 2, 3]}} )

The important keyword here is $pushAll. You can use it to add items to arrays inside of a single record attribute.

这里的重要关键字是$pushAll。您可以使用它向单个记录属性内的数组添加项目。

回答by Nate Ferrero

If you want to update multiple records, it's important to pass trueas the 4th argument to the update function:

如果你想更新多条记录,重要的true是将第四个参数传递给更新函数:

db.test.update( {"name": "x"}, {"$pushAll": {"arr": [1, 2, 3]}}, false, true)

Per the MongoDB shell syntax for update():

根据 update() 的 MongoDB shell 语法:

db.collection.update( criteria, objNew, upsert, multi )
  • upsert- if the record(s) do not exist, insert one. Upsert only inserts a single document
  • mutli- indicates if all documents matching criteria should be updated rather than just one
  • upsert- 如果记录不存在,插入一个。Upsert 只插入一个文档
  • mutli- 指示是否应该更新所有符合条件的文档,而不仅仅是一个

回答by James Mallon

the simplest approach is by using a conventional update operation

最简单的方法是使用传统的更新操作

  db.urColl.update(
    { x: "h" },
    { $push: { arr: { $each: [6,8] } } },
    { multi: true }
  );`

回答by krekto

$pushAll
Deprecated since version 2.4: Use the $pushoperator with $eachinstead.

$pushAll
2.4 版后已弃用:使用$push运算符 with$each代替。

The $pushAlloperator appends the specified values to an array.

所述$pushAll操作者将指定值的数组。

The $pushAlloperator has the form:

$pushAll运营商的形式为:

{ $pushAll: { <field>: [ <value1>, <value2>, ... ] } }

If you specify a single value, $pushAllwill behave as $push.

如果您指定单个值,$pushAll则将表现为$push.