包括所有现有字段并向文档添加新字段 [英] Include all existing fields and add new fields to document
问题描述
我想定义一个$ project聚合阶段,可以指示它添加一个新字段并包括所有现有字段,而不必列出所有现有字段.
I would like to define a $project aggregation stage where I can instruct it to add a new field and include all existing fields, without having to list all the existing fields.
我的文档如下所示,其中包含许多字段:
My document looks like this, with many fields:
{
obj: {
obj_field1: "hi",
obj_field2: "hi2"
},
field1: "a",
field2: "b",
...
field26: "z"
}
我要进行这样的聚合操作:
I want to make an aggregation operation like this:
[
{
$project: {
custom_field: "$obj.obj_field1",
//the next part is that I don't want to do
field1: 1,
field2: 1,
...
field26: 1
}
},
... //group, match, and whatever...
]
在这种情况下,是否可以使用类似包括所有字段"这样的关键字,或者可以通过其他方式避免单独列出每个字段?
Is there something like an "include all fields" keyword that I can use in this case, or some other way to avoid having to list every field separately?
推荐答案
在4.2及更高版本中,您可以使用 $addFields
已在3.4
In 4.2+, you can use the $set
aggregation pipeline operator which is nothing other than an alias to $addFields
added in 3.4
$addFields
阶段等效于$project
阶段,在输入文档中明确指定所有现有字段并添加新字段.
The
$addFields
stage is equivalent to a$project
stage that explicitly specifies all existing fields in the input documents and adds the new fields.
db.collection.aggregate([
{ "$addFields": { "custom_field": "$obj.obj_field1" } }
])
这篇关于包括所有现有字段并向文档添加新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!