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

{
    "_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

推荐答案

正如您所猜测的,$project允许您这样做:

db.col.aggregate([
{
    $project : 
    {
        _id: "$command._id",
        name: "$command.name", 
        strike: "$command.strike", 
        duration: "$command.duration"
    }
}
]).pretty()

我插入了您以前的结果,上面的查询返回了以下结果:

{
    "_id" : ObjectId("57ec6b6f6c61e919b578fe7c"),
    "name" : "Run",
    "strike" : 15,
    "duration" : 123
}
{
    "_id" : ObjectId("573d688d080cc2cbe8aecbbc"),
    "name" : "Run",
    "strike" : 12,
    "duration" : 597
}

所以piping用这个$product进行查询应该会得到你想要的结果.

Update after comments

如果您主要关心的不是确切的 struct ,而是排除几个字段(不必列出要包含的所有字段),那么您可以使用find()而不是aggregate().

aggregate's product only lets you exclude _id. This means you need to manually list all fields to include.
Note: Since version 3.4 of MongoDB it is possible to exclude fields in $project phase (https://docs.mongodb.com/manual/reference/operator/aggregation/project/#exclude-fields)

但是,find允许您列出要隐藏的字段.

可供替代的

(1)您可以使用$out将聚合结果重定向到另一个集合:

{ $out : "commands" }

(2)即使 struct 不完全符合您的要求,您也可以执行find次查询并隐藏字段:

db.commands.find({}, {_id:0, "command.score":0, eventname:0}).pretty()

它会返回这个,这与你想要的非常接近:

{
    "command" : {
        "_id" : ObjectId("57ec6b6f6c61e919b578fe7c"),
        "name" : "Run",
        "strike" : 15,
        "duration" : 123
    }
}

Mongodb相关问答推荐

用Spring Boot查询MongoDB中的对象数组

如何用Python和MongoDB找到单据字段的最大值?

如何从集合中移除所有匹配的数组项?

mongo如何通过聚合加载嵌套文档

从 mongodb Golang 检索时判断零等效时间.时间

Mongodb聚合中基于其他字段值的多个条件的动态新字段值

在mongoose 中按键查找嵌套对象

MongoDB 查询以包含多个字段的最常见值的计数

MongoDB 支持的最 Big Data 库数

Mongoexport 在日期范围内使用 $gt 和 $lt 约束

mongodb 模式设计命名约定

Flask and Mongo

django 和 mongodb 是否使迁移成为过go ?

为什么不建议在 MongoDB 中使用服务器端存储函数?

具有简单密码认证的 MongoDB 副本集

从每个组中 Select 前 N 行

无法连接到远程服务器上的 mongo

Mongodb $lookup 使用 _id 无效果

如何在mongoose的嵌套填充中 Select 特定字段

无法从 mongodb 中删除集合