[英]How to convert array of objects into nested object in MongoDB aggregation pipeline
[英]How to convert array to object without keys on aggregation query of MongoDB?
我有这样的查询结果;
{
"content" : [
"X",
"1"
]
}
我的查询就是这样;
db.getCollection("x").aggregate([
{$group : {_id : null, tN: {$addToSet : { content: [ "$tN", "$pC" ] }}}},
{$unwind: "$tN"},
{$replaceRoot: {newRoot: '$tN'}}
])
如何将该内容数组转换为;
{
"tN" : "X",
"pC" : "1"
}
您可以在$project阶段使用$arrayElemAt获取它
db.getCollection("x").aggregate([
{
$group: {
_id: null,
tN: { $addToSet: { content: [ "$tN", "$pC" ] } }
}
},
{
$unwind: "$tN"
},
{
$replaceRoot: { newRoot: "$tN" }
},
{
$project: {
_id: 0,
"tN": {
$arrayElemAt: [ "$content", 0 ]
},
"pC": {
$arrayElemAt: [ "$content", 1 ]
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.