[英]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.