我想定义一个 $project 聚合阶段,我可以指示它添加一个新字段并包含所有现有字段,而不必列出所有现有字段。
我的文档看起来像这样,有很多字段:
{
obj: {
obj_field1: "hi",
obj_field2: "hi2"
},
field1: "a",
field2: "b",
...
field26: "z"
}
我想做一个这样的聚合操作:
[
{
$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...
]
在这种情况下,我是否可以使用类似“包含所有字段”的关键字,或者通过其他方式避免必须单独列出每个字段?
最佳答案
在 4.2+ 中,您可以使用 $set
聚合管道运算符,它只不过是 $addFields
的别名在 3.4 中添加
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" } }
])
https://stackoverflow.com/questions/19431773/
相关文章:
linux - 如何避免来自 mongodb 的 transparent_hugepage/defr
java - 获取带有 Java 驱动程序的 mongoDB 中最后插入的文档的 ID
node.js - 如何使用 Mongoose 删除数据库?
mongodb - 基于文档和基于键/值的数据库之间的区别?
javascript - 有没有办法将 'pretty' 打印 MongoDB shell 输出到文
mongodb - 与关系数据库相比,使用像 MongoDB 这样的无模式数据库有什么优势?