[英]How to convert an array of elements to an object in a MongoDB projection
I tried to use $project
and $arrayToObject
but I can't figure how it works.我尝试使用
$project
和$arrayToObject
但我不知道它是如何工作的。 My MongoDB query returns an array of objects:我的 MongoDB 查询返回一个对象数组:
[{ amounts: [ 10, 20, 30 ], id: "0x3c93" }, { amounts: [ 0, 0, 100 ], id: "0xee10" }]
And I want to group the results by "id" as key and "amounts" as value:我想将结果按“id”作为键和“金额”作为值进行分组:
{"0x3c93": [ 10, 20, 30 ], "0xee10": [ 0, 0, 100 ]}
What is the correct expression to achieve this projection?实现这个投影的正确表达是什么? I am using the node.js driver.
我正在使用 node.js 驱动程序。
One option is to $group
them to an array and format them to k
, v
before using $arrayToObject
:一种选择是在使用
$arrayToObject
之前将它们$group
到一个数组中并将它们格式化为k
, v
:
db.collection.aggregate([
{$group: {_id: 0, data: {$push: {k: "$id", v: "$amounts"}}}},
{$project: {_id: 0, data: {$arrayToObject: "$data"}}},
{$replaceRoot: {newRoot: "$data"}}
])
See how it works on the playground example看看它在操场上的例子是如何工作的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.