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

查看:21
本文介绍了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需要指定通过哪些字段,$addFields 将返回所有字段并添加或替换指定字段.

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天全站免登陆