Database Manual / Reference / Query Language / Update / Arrays

$push (update operator)(更新运算符)

Definition定义

$push
The $push operator appends a specified value to an array.$push运算符将指定值附加到数组中。

Compatibility兼容性

You can use $push for deployments hosted in the following environments:您可以将$push用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The $push operator has the form:$push运算符的形式如下:

{ $push: { <field1>: <value1>, ... } }

To specify a <field> in an embedded document or in an array, use dot notation.要在嵌入式文档或数组中指定<field>,请使用点符号

Behavior行为

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.从MongoDB 5.0开始,更新运算符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。有关详细信息,请参阅更新运算符行为

If the field is absent in the document to update, $push adds the array field with the value as its element.如果要更新的文档中缺少该字段,则$push会添加具有值的数组字段作为其元素。

If the field is not an array, the operation will fail.如果字段不是数组,则操作将失败。

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push. 如果该值是一个数组,则$push会将整个数组附加为单个元素。要单独添加值的每个元素,请将$each修饰符与$push一起使用。For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push, see Modifiers.例如,请参阅在多个文档中将值附加到数组。有关可用于$push的修饰符列表,请参见修饰符

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $push with an empty operand expression ( { } ). 从MongoDB 5.0开始,当您使用带有空操作数表达式({ })的更新运算符(如$push)时,mongod不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。

Modifiers修饰符

You can use the $push operator with the following modifiers:您可以将$push运算符与以下修饰符一起使用:

Modifier修饰符Description描述
$eachAppends multiple values to the array field.将多个值附加到数组字段。
$sliceLimits the number of array elements. Requires the use of the $each modifier.限制数组元素的数量。需要使用$each修饰符。
$sortOrders elements of the array. Requires the use of the $each modifier.对数组的元素进行排序。需要使用$each修饰符。
$positionSpecifies the location in the array at which to insert the new elements. 指定数组中插入新元素的位置。Requires the use of the $each modifier. 需要使用$each修饰符。Without the $position modifier, the $push appends the elements to the end of the array.如果没有$position修饰符,$push会将元素附加到数组的末尾。

When used with modifiers, the $push operator has the form:当与修饰符一起使用时,$push运算符的形式如下:

{ $push: { <field1>: { <modifier1>: <value1>, ... }, ... } }

The processing of the $push operation with modifiers occur in the following order, regardless of the order in which the modifiers appear:带有修饰符的$push操作的处理按以下顺序进行,而不管修饰符出现的顺序如何:

  1. Update array to add elements in the correct position.更新数组以在正确位置添加元素。
  2. Apply sort, if specified.如果指定,则应用排序。
  3. Slice the array, if specified.如果指定,则对数组进行分片。
  4. Store the array.存储数组。

Examples示例

Create the students collection:创建students集合:

db.students.insertOne( { _id: 1, scores: [ 44, 78, 38, 80 ] } )

Append a Value to an Array将值附加到数组

The following example appends 89 to the scores array:以下示例将89附加到scores数组中:

db.students.updateOne(
{ _id: 1 },
{ $push: { scores: 89 } }
)

Example output:示例输出:

{ _id: 1, scores: [ 44, 78, 38, 80, 89 ] }

Append a Value to Arrays in Multiple Documents在多个文档中为数组添加值

Add the following documents to the students collection:将以下文档添加到students集合中:

db.students.insertMany( [
{ _id: 2, scores: [ 45, 78, 38, 80, 89 ] } ,
{ _id: 3, scores: [ 46, 78, 38, 80, 89 ] } ,
{ _id: 4, scores: [ 47, 78, 38, 80, 89 ] }
] )

The following $push operation appends 95 to the scores array in each document:以下$push操作将95附加到每个文档中的scores数组中:

db.students.updateMany(
{ },
{ $push: { scores: 95 } }
)

To confirm that each scores array includes 95, run the following operation:要确认每个scores数组包括95,请运行以下操作:

db.students.find()

The operation returns the following results:该操作返回以下结果:

[
{ _id: 1, scores: [ 44, 78, 38, 80, 89, 95 ] },
{ _id: 2, scores: [ 45, 78, 38, 80, 89, 95 ] },
{ _id: 3, scores: [ 46, 78, 38, 80, 89, 95 ] },
{ _id: 4, scores: [ 47, 78, 38, 80, 89, 95 ] }
]

Append Multiple Values to an Array将多个值附加到数组

Use $push with the $each modifier to append multiple values to the array field.使用$tush$teach修饰符将多个值附加到数组字段。

The following example appends each element of [ 90, 92, 85 ] to the scores array for the document where the name field equals joe:以下示例将[90,92,85]的每个元素附加到name字段等于joe的文档的scores数组中:

db.students.updateOne(
{ name: "joe" },
{ $push: { scores: { $each: [ 90, 92, 85 ] } } }
)

Use $push Operator with Multiple Modifiers使用带有多个修饰符的$push运算符

Add the following document to the students collection:将以下文档添加到students集合中:

db.students.insertOne(
{
"_id" : 5,
"quizzes" : [
{ "wk": 1, "score" : 10 },
{ "wk": 2, "score" : 8 },
{ "wk": 3, "score" : 5 },
{ "wk": 4, "score" : 6 }
]
}
)

The following $push operation uses:以下$push操作使用:

  • the $each modifier to add multiple documents to the quizzes array,$each修饰符用于将多个文档添加到quizzes数组中,
  • the $sort modifier to sort all the elements of the modified quizzes array by the score field in descending order, and$sort修饰符,用于按score字段降序对修改后的quizzes数组的所有元素进行排序,以及
  • the $slice modifier to keep only the first three sorted elements of the quizzes array.$slice修饰符仅保留quizzes数组的前三个已排序的元素。
db.students.updateOne(
{ _id: 5 },
{
$push: {
quizzes: {
$each: [ { wk: 5, score: 8 }, { wk: 6, score: 7 }, { wk: 7, score: 6 } ],
$sort: { score: -1 },
$slice: 3
}
}
}
)

After the operation only the three highest scoring quizzes are in the array:操作后,数组中只有三个得分最高的测验:

{
"_id" : 5,
"quizzes" : [
{ "wk" : 1, "score" : 10 },
{ "wk" : 2, "score" : 8 },
{ "wk" : 5, "score" : 8 }
]
}