首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >聚合/项目子文档作为mongo中的顶级文档

聚合/项目子文档作为mongo中的顶级文档
EN

Stack Overflow用户
提问于 2016-10-11 08:38:17
回答 1查看 14.8K关注 0票数 16

在我的一个集合中执行了几个聚合步骤(管道步骤)之后,我得到了以下结果:

代码语言:javascript
复制
{
    "_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
    }
}

这很好!

但是,在聚合的下一步中,我希望得到以下结果:

代码语言:javascript
复制
{
    "_id" : ObjectId("57ec6b6f6c61e919b578fe7c"),
    "name" : "Run",
    "strike" : 15,
    "duration" : 123
}
{
    "_id" : ObjectId("573d688d080cc2cbe8aecbbc"),
    "name" : "Run",
    "strike" : 12,
    "duration" : 597
}

如果您注意到了,command字段应该成为顶级文档,并且应该跳过command.score

我如何在一个步骤中实现这一点?如果这在单个步骤中是不可能的,那么在多个步骤中呢?我想我必须使用$project

EN

回答 1

Stack Overflow用户

发布于 2019-06-10 00:38:02

Mongo 4.2开始,可以使用$replaceWith聚合操作符将一个文档替换为另一个文档(在我们的例子中是一个子文档),作为$replaceRoot的语法糖。

代码语言:javascript
复制
// { "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的替代语法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39968790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档