本文介绍了如何在MongoDB中将数组转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组,其中包含未知数量的数组元素:
{ "内容": [{"_id": "参考书",总计":189,已发表":189,创建":0,批准":0,拒绝":0,sent_for_approval":0},{"_id": "网络链接",总计":1911,发表":1899,创建":10,批准":2,拒绝":0,sent_for_approval":0},.................]}
我想将其转换为给定的对象:
{内容":{{"_id": "参考书",总计":189,已发表":189,创建":0,批准":0,拒绝":0,sent_for_approval":0},{"_id": "网络链接",总计":1911,发表":1899,创建":10,批准":2,拒绝":0,sent_for_approval":0},.................}}
我尝试使用 $unwind,但没有得到所需的输出.如何在 MongoDB 中实现这个内部聚合管道?
我使用的是 Mongo 3.4 版.
解决方案
我找到了解决方案.
{$项目:{内容": {$arrayToObject":{$地图":{输入":$内容","as": "el",在": {"k": "$$el._id","v": "$$el"}}}}}I have an array of object as given with unknown number of array elements:
{ "content": [
{
"_id": "refbooks",
"total": 189,
"published": 189,
"created": 0,
"approved": 0,
"rejected": 0,
"sent_for_approval": 0
},
{
"_id": "weblinks",
"total": 1911,
"published": 1899,
"created": 10,
"approved": 2,
"rejected": 0,
"sent_for_approval": 0
},.................]}
I want to convert it to an object like given:
{ "content": {
{
"_id": "refbooks",
"total": 189,
"published": 189,
"created": 0,
"approved": 0,
"rejected": 0,
"sent_for_approval": 0
},
{
"_id": "weblinks",
"total": 1911,
"published": 1899,
"created": 10,
"approved": 2,
"rejected": 0,
"sent_for_approval": 0
},.................}}
I tried using $unwind, but I did't get my required output.How to implement this inside aggregation pipeline in MongoDB?
I'm using Mongo version 3.4.
解决方案
I found the solution.
{
$project: {
"content": {
"$arrayToObject": {
"$map": {
"input": "$content",
"as": "el",
"in": {
"k": "$$el._id",
"v": "$$el"
}
}
}
}
}
这篇关于如何在MongoDB中将数组转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!