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

时间:2019-08-10 01:44:26

标签: mongodb mongoose

我在mongodb聚合管道中有一个小组阶段,如下所示:

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

输出看起来像这样:

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

请注意,creator是一个数组。我希望它只是一个对象。由于某种原因,这并不容易做到(可能是,但是我无法弄清楚)。这是我尝试过的:

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

但是它不起作用。如何将creator数组转换为对象?

1 个答案:

答案 0 :(得分:0)

我知道了:

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