在我的一个集合中执行了几个聚合步骤(管道步骤)之后,我得到了以下结果:
{
"_id" : ObjectId("574e7722bffe901713d383bb"),
"eventname" : "Ball Passed",
"command" : {
"_id" : ObjectId("57ec6b6f6c61e919b578fe7c"),
"name" : "Run",
"strike" : 15,
"score" : true,
"duration" : 123
}
}
{
"_id" : ObjectId("57ec6b6f6c61e919b578ff8a"),
"eventname" : "Ball Passed",
"command" : {
"_id" : ObjectId("573d688d080cc2cbe8aecbbc"),
"name" : "Run",
"strike" : 12,
"score" : false,
"duration" : 597
}
}
这很好!
但是,在聚合的下一步中,我希望得到以下结果:
{
"_id" : ObjectId("57ec6b6f6c61e919b578fe7c"),
"name" : "Run",
"strike" : 15,
"duration" : 123
}
{
"_id" : ObjectId("573d688d080cc2cbe8aecbbc"),
"name" : "Run",
"strike" : 12,
"duration" : 597
}
如果您注意到了,command
字段应该成为顶级文档,并且应该跳过command.score
。
我如何在一个步骤中实现这一点?如果这在单个步骤中是不可能的,那么在多个步骤中呢?我想我必须使用$project
发布于 2019-06-10 00:38:02
从Mongo 4.2
开始,可以使用$replaceWith
聚合操作符将一个文档替换为另一个文档(在我们的例子中是一个子文档),作为$replaceRoot
的语法糖。
// { "eventname": "Ball Passed", "command": { "_id": "57e...", "name": "Run", "strike": 15, "score": true, "duration": 123 } }
// { "eventname": "Ball Passed", "command": { "_id": "573...", "name": "Run", "strike": 12, "score": false, "duration": 597 } }
db.collection.aggregate([
{ $replaceWith: "$command" }, // replaces the document by the content of "command"
{ $unset: ["score"] } // drops the "score" field
])
// { "_id" : "57e...", "name" : "Run", "strike" : 15, "duration" : 123 }
// { "_id" : "573...", "name" : "Run", "strike" : 12, "duration" : 597 }
还要注意Mongo 4.2
中引入的$unset
聚合运算符,当仅用于删除字段时,它是$project
的替代语法。
https://stackoverflow.com/questions/39968790
复制相似问题