简体   繁体   English

如何在聚合管道的$ group阶段将数组转换为对象?

[英]How can I convert an array to an object in the $group stage of an aggregation pipeline?

I have a group stage in a mongodb aggregation pipeline that looks like this: 我在mongodb聚合管道中有一个小组阶段,如下所示:

$group: {
    _id: null,
    comments: {
        $push: {
            _id: "$comments._id", 
            comment: "$comments.comment",
            creator: "$comments.creator"
        }
    }
}

The output looks like this: 输出看起来像这样:

{
    "_id": null,
    comments: [{
        "_id": "5c113250b54e8a5bc4412a9a",
        "comment": "This is my comment",
        "creator": [{
            "_id": "5c113250b54e8a5bb9252a7b",
            "name": "John Doe"
        }, ...]
    }]
}

Notice that creator is an array. 请注意, creator是一个数组。 I want it to just be an object. 我希望它只是一个对象。 For some reason this isn't easy to do (it probably is, but I can't figure it out). 由于某种原因,这并不容易做到(可能是,但是我无法弄清楚)。 Here is what I've tried: 这是我尝试过的:

$group: {
    _id: null,
    comments: {
        $push: {
            _id: "$comments._id", 
            comment: "$comments.comment",
            creator: {$arrayToObject: "$comments.creator"}
        }
    }
}

But it doesn't work. 但这是行不通的。 How can I convert the creator array to an object? 如何将creator数组转换为对象?

我想到了:

creator: { $arrayElemAt: [ "$comments.creator", 0 ] }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Mongo聚合管道:如何在后续阶段访问一个小组阶段变量? - Mongo aggregation pipeline : How can I access one group stage variable in subsequent stage? 如何在MongoDB聚合管道中将对象数组转换为嵌套对象 - How to convert array of objects into nested object in MongoDB aggregation pipeline 如何在组方法中在 Mongodb 聚合管道中使用正则表达式? - How can i use regex in Mongodb aggregation pipeline in group method? 如何使用 C# 和 Mongo 聚合管道在项目阶段完成字符串连接? - How can I complete a string concatenation inside a project stage using C# and the Mongo aggregation pipeline? How can i convert the mongoose aggregation array of object of object response into json object response - How can i convert the mongoose aggregation array of object of object response into json object response 如何在一个聚合管道阶段进行计数并在稍后阶段使用它? - How do I take a count in one aggregation pipeline stage and use it in a later stage? 具有对象推送的Morphia聚合阶段组 - Morphia aggregation stage group with object push 如何在 MongoDB 聚合管道中将对象/子文档数组转换为字符串数组? - How do I convert an array of objects / subdocuments to an array of strings in a MongoDB Aggregation pipeline? 如何在 $match 聚合中找到一组值并将结果分组? - how can I find an array of values in a $match aggregation and group the result? 在java spring中使用$ group stage实现MongoDB聚合管道 - Implement MongoDB aggregation pipeline with $group stage in java spring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM