MongoDB:使用静态值聚合 $project 添加字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15110822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB: aggregate $project add field with static value
提问by redexp
Can I somehow add custom field with static (not computed) value?
我可以以某种方式添加具有静态(未计算)值的自定义字段吗?
I want to prepare objects before send and I need to remove some fields with internal information and add field with some entity ID.
我想在发送之前准备对象,我需要删除一些带有内部信息的字段并添加带有一些实体 ID 的字段。
For example I have collection "test" with objects like this
例如,我有像这样的对象的集合“测试”
{_id: ObjectId(...), data: {...}}
And I need to convert it to
我需要将其转换为
{data: {...}, entity_id: 54}
So how can I add entity_id: 54 without looping over result in my code?
那么如何添加 entity_id: 54 而不在我的代码中循环结果?
db.test.aggregate({ $project: {_id: 0, data: 1, entity_id: ? } })
Thanks
谢谢
回答by Elad
回答by Asya Kamsky
editas of 2.6 the $literal
expression exists so you don't have to use the workaround now.
从 2.6 开始编辑$literal
表达式存在,因此您现在不必使用解决方法。
Original answer: I know this may sound really dumb, but you can use a "no-op" expression to "compute" what you need.
原始答案:我知道这听起来可能很愚蠢,但是您可以使用“无操作”表达式来“计算”您需要的内容。
Example:
例子:
db.test.aggregate( { $project : {_id:0, data:1, entity_id: {$add: [54]} } } )
There was a proposed $literal
operator for exactly this use case but it hasn't been implemented yet, you can vote for it here.
有一个$literal
针对此用例的建议运算符,但尚未实施,您可以在此处投票。