$set (aggregation)
On this page本页内容
Definition定义
$set
New in version 4.2.4.2版新增。Adds new fields to documents.向文档中添加新字段。$set
outputs documents that contain all existing fields from the input documents and newly added fields.$set
输出文档,该文档包含输入文档和新添加的字段中的所有现有字段。The$set
stage is an alias for$addFields
.$set
阶段是$addFields
的别名。Both stages are equivalent to a这两个阶段都相当于$project
stage that explicitly specifies all existing fields in the input documents and adds the new fields.$project
阶段,该阶段显式指定输入文档中的所有现有字段并添加新字段。
Syntax语法
$set
has the following form:具有以下形式:
{ $set: { <newField>: <expression>, ... } }
Specify the name of each field to add and set its value to an aggregation expression or an empty object. 指定要添加的每个字段的名称,并将其值设置为聚合表达式或空对象。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
If the name of the new field is the same as an existing field name (including 如果新字段的名称与现有字段名称(包括_id
), $set
overwrites the existing value of that field with the value of the specified expression._id
)相同,则$set
会用指定表达式的值覆盖该字段的现有值。
Behavior行为
$set
appends new fields to existing documents.将新字段附加到现有文档中。You can include one or more您可以在聚合操作中包括一个或多个$set
stages in an aggregation operation.$set
阶段。$set
accepts the embedding of objects where you can set a value to an aggregation expression or to an empty object.接受对象的嵌入,您可以在其中为聚合表达式或空对象设置值。For example, the following nested objects are accepted:例如,接受以下嵌套对象:{$set: { a: { b: { } } } }
To add a field or fields to embedded documents (including documents in arrays) use the dot notation. See example.要向嵌入文档(包括数组中的文档)添加一个或多个字段,请使用点表示法。请参见示例。To add an element to an existing array field with要使用$set
, use with$concatArrays
. See example.$set
将元素添加到现有的数组字段中,请与$concatArrays
一起使用。请参见示例。
Examples实例
Using Two $set
Stages使用两个$set
阶段
$set
StagesCreate a sample 创建一个包含以下内容的样例scores
collection with the following:scores
集合:
db.scores.insertMany([
{ _id: 1, student: "Maya", homework: [ 10, 5, 10 ], quiz: [ 10, 8 ], extraCredit: 0 },
{ _id: 2, student: "Ryan", homework: [ 5, 6, 5 ], quiz: [ 8, 8 ], extraCredit: 8 }
])
The following operation uses two 以下操作使用两个$set
stages to include three new fields in the output documents:$set
阶段在输出文档中包括三个新字段:
db.scores.aggregate( [
{
$set: {
totalHomework: { $sum: "$homework" },
totalQuiz: { $sum: "$quiz" }
}
},
{
$set: {
totalScore: { $add: [ "$totalHomework", "$totalQuiz", "$extraCredit" ] } }
}
] )
The operation returns the following documents:该操作返回以下文档:
{
"_id" : 1,
"student" : "Maya",
"homework" : [ 10, 5, 10 ],
"quiz" : [ 10, 8 ],
"extraCredit" : 0,
"totalHomework" : 25,
"totalQuiz" : 18,
"totalScore" : 43
}
{
"_id" : 2,
"student" : "Ryan",
"homework" : [ 5, 6, 5 ],
"quiz" : [ 8, 8 ],
"extraCredit" : 8,
"totalHomework" : 16,
"totalQuiz" : 16,
"totalScore" : 40
}
Adding Fields to an Embedded Document向嵌入文档添加字段
Use dot notation to add new fields to embedded documents.使用点表示法将新字段添加到嵌入文档中。
Create a sample collection 创建具有以下内容的样本集合vehicles
with the following:vehicles
(车辆):
db.vehicles.insertMany([
{ _id: 1, type: "car", specs: { doors: 4, wheels: 4 } },
{ _id: 2, type: "motorcycle", specs: { doors: 0, wheels: 2 } },
{ _id: 3, type: "jet ski" }
])
The following aggregation operation adds a new field 以下聚合操作将一个新字段fuel_type
to the embedded document specs
.fuel_type
添加到嵌入的文档specs
中。
db.vehicles.aggregate( [
{ $set: { "specs.fuel_type": "unleaded" } }
] )
The operation returns the following results:该操作返回以下结果:
{ _id: 1, type: "car", specs: { doors: 4, wheels: 4, fuel_type: "unleaded" } }
{ _id: 2, type: "motorcycle", specs: { doors: 0, wheels: 2, fuel_type: "unleaded" } }
{ _id: 3, type: "jet ski", specs: { fuel_type: "unleaded" } }
Overwriting an existing field覆盖现有字段
Specifying an existing field name in a 在$set
operation causes the original field to be replaced.$set
操作中指定现有字段名会导致替换原始字段。
Create a sample collection called 创建一个名为animals
with the following:animals
的样本集合,包含以下内容:
db.animals.insertOne( { _id: 1, dogs: 10, cats: 15 } )
The following 以下$set
operation overrides the cats
field:$set
操作将覆盖cats
字段:
db.animals.aggregate( [
{ $set: { "cats": 20 } }
] )
The operation returns the following document:该操作返回以下文档:
{ _id: 1, dogs: 10, cats: 20 }
It is possible to replace one field with another. 可以用另一个字段替换一个字段。In the following example the 在下面的示例中,item
field substitutes for the _id
field.item
字段替换_id
字段。
Create a sample collection called 创建一个名为fruits
contains the following documents:fruits
的示例集合,其中包含以下文档:
db.fruits.insertMany([
{ "_id" : 1, "item" : "tangerine", "type" : "citrus" },
{ "_id" : 2, "item" : "lemon", "type" : "citrus" },
{ "_id" : 3, "item" : "grapefruit", "type" : "citrus" }
])
The following aggregration operation uses 下面的聚合操作使用$set
to replace the _id
field of each document with the value of the item
field, and replaces the item
field with a string "fruit"
.$set
将每个文档的_id
字段替换为item
字段的值,并将item
字段替换成字符串"fruit"
。
db.fruits.aggregate( [
{ $set: { _id : "$item", item: "fruit" } }
] )
The operation returns the following:该操作返回以下内容:
{ "_id" : "tangerine", "item" : "fruit", "type" : "citrus" }
{ "_id" : "lemon", "item" : "fruit", "type" : "citrus" }
{ "_id" : "grapefruit", "item" : "fruit", "type" : "citrus" }
Add Element to an Array将元素添加到数组
Create a sample 创建一个包含以下内容的样例scores
collection with the following:scores
集合:
db.scores.insertMany([
{ _id: 1, student: "Maya", homework: [ 10, 5, 10 ], quiz: [ 10, 8 ], extraCredit: 0 },
{ _id: 2, student: "Ryan", homework: [ 5, 6, 5 ], quiz: [ 8, 8 ], extraCredit: 8 }
])
You can use 可以将$set
with a $concatArrays
expression to add an element to an existing array field. $set
与$concatArrays
表达式一起使用,将元素添加到现有的数组字段中。For example, the following operation uses 例如,以下操作使用$set
to replace the homework
field with a new array whose elements are the current homework
array concatenated with another array containing a new score [ 7 ]
.$set
将homework
字段替换为一个新数组,该数组的元素是与包含新分数的另一个数组[7]
连接的当前homework
数组。
db.scores.aggregate([
{ $match: { _id: 1 } },
{ $set: { homework: { $concatArrays: [ "$homework", [ 7 ] ] } } }
])
The operation returns the following:该操作返回以下内容:
{ "_id" : 1, "student" : "Maya", "homework" : [ 10, 5, 10, 7 ], "quiz" : [ 10, 8 ], "extraCredit" : 0 }
Creating a New Field with Existing Fields使用现有字段创建新字段
Create a sample 创建一个包含以下内容的样例scores
collection with the following:scores
集合:
db.scores.insertMany([
{ _id: 1, student: "Maya", homework: [ 10, 5, 10 ], quiz: [ 10, 8 ], extraCredit: 0 },
{ _id: 2, student: "Ryan", homework: [ 5, 6, 5 ], quiz: [ 8, 8 ], extraCredit: 8 }
])
The following aggregation operation adds a new field 以下聚合操作向包含quizAverage
to each document that contains the average of the quiz
array.quiz
数组平均值的每个文档添加一个新字段quizAverage
。
db.scores.aggregate( [
{
$set: {
quizAverage: { $avg: "$quiz" }
}
}
] )
The operation returns the following documents:该操作返回以下文档:
[
{
_id: 1,
student: 'Maya',
homework: [ 10, 5, 10 ],
quiz: [ 10, 8 ],
extraCredit: 0,
quizAverage: 9
},
{
_id: 2,
student: 'Ryan',
homework: [ 5, 6, 5 ],
quiz: [ 8, 8 ],
extraCredit: 8,
quizAverage: 8
}
]