包括所有现有字段并将新字段添加到文档 [英] Include all existing fields and add new fields to document

查看:26
本文介绍了包括所有现有字段并将新字段添加到文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个 $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+ 中,您可以使用 $set 聚合管道操作符,它只不过是 $addFields在 3.4 中添加

In 4.2+, you can use the $set aggregation pipeline operator which is nothing other than an alias to $addFieldsadded 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屋!

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