MongoDB $ project:保留以前的管道字段 [英] MongoDB $project: Retain previous pipeline fields

查看:273
本文介绍了MongoDB $ project:保留以前的管道字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB投影中,是否可以指定一些新字段(但同时保留输入到管道的投影阶段的字段)?我没有重命名任何现有字段.

Is there a way, in a MongoDB projection, to specify some new fields (but at the same time, retain fields that were input to the projection stage of the pipeline)? I'm not renaming any of the existing fields.

因此,如果我从具有"field1"和"field2"的集合开始,并进行以下投影:

So if I start with a collection that has 'field1' and 'field2', and do the following projection:

{ $project: { field3: { $gt: ['$field1', 10] } } }

我想最后以'field1','field2'和'field3'作为下一个阶段的输入或聚合框架的输出.

I want to end up with 'field1', 'field2', and 'field3' present as input to the next stage, or output from the aggregation framework.

我试图通过排除_id将投影置于排除模式,但这不起作用.

I attempted to put the projection into exclusion mode by excluding _id, but that doesn't work.

推荐答案

其中$project需要指定要传递的字段,

where $project needs to specify which fields to pass through, $addFields will return all fields and add or replace specified fields.

{ $addFields: { field3: { $gt: ['$field1', 10] } } }

将完全实现您想要的.

请注意,此功能已在Mongo 3.4版中添加.

Please note, this feature was added in Mongo version 3.4.

这篇关于MongoDB $ project:保留以前的管道字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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