MongoDb聚合运算符$arrayToObject
可以将一个数组转换为文档。注意只有两种数组才可以转换为文档,参见$arrayToObject使用
。
{ $arrayToObject: <expression> }
必须是数组或能够被解析为数组的表达式,而且数组元素要么是只有两个元素的数组,要么是包含k
、v
两个字段的文档数组。
注意,不是所有的数组表达式都能转换为文档,只有下面两种数组才可以进行转换:
只有两个元素的数组,第一个元素为字段名,第二个元素为字段值:
[ [ [ "item", "abc123" ], [ "qty", 25 ] ] ]
包含两个字段的文档数组,一个字段是k
一个字段是v
:
k
包含了字段名v
包含了字段值[ [ { "k": "item", "v": "abc123" }, { "k": "qty", "v": 25 } ] ]
例子 | 返回 |
---|---|
{ $arrayToObject: [[ { "k": "item", "v": "abc123" }, { "k": "qty", "v": "$qty" } ]] } |
当文档字段qty 的值为25时,返回:{ "item" : "abc123", "qty" : 25 } |
{ $arrayToObject: { $literal: [[ "item", "abc123" ], [ "qty",25 ]] } } |
{ "item" : "abc123", "qty" : 25 } |
{ $arrayToObject: { $literal: [ { "k": "item", "v": "123abc" }, { "k": "item", "v": "abc123" }] } } |
{ "item" : "abc123" } |
集合inventory
中有下面的文档:
{ "_id" : 1, "item" : "ABC1", dimensions: [ { "k": "l", "v": 25} , { "k": "w", "v": 10 }, { "k": "uom", "v": "cm" } ] }
{ "_id" : 2, "item" : "ABC2", dimensions: [ [ "l", 50 ], [ "w", 25 ], [ "uom", "cm" ] ] }
{ "_id" : 3, "item" : "ABC3", dimensions: [ [ "l", 25 ], [ "l", "cm" ], [ "l", 50 ] ] }
下面的聚合管道使用$arrayToObject
将dimensions
数组字段转换为文档:
db.inventory.aggregate(
[
{
$project: {
item: 1,
dimensions: { $arrayToObject: "$dimensions" }
}
}
]
)
操作返回下面的结果:
{ "_id" : 1, "item" : "ABC1", "dimensions" : { "l" : 25, "w" : 10, "uom" : "cm" } }
{ "_id" : 2, "item" : "ABC2", "dimensions" : { "l" : 50, "w" : 25, "uom" : "cm" } }
{ "_id" : 3, "item" : "ABC3", "dimensions" : { "l" : 50 } }
集合inventory
有下列文档:
{ "_id" : 1, "item" : "ABC1", instock: { warehouse1: 2500, warehouse2: 500 } }
{ "_id" : 2, "item" : "ABC2", instock: { warehouse2: 500, warehouse3: 200} }
下面的聚合操作计算了所有条目的股票之和,并将其添加到instock
文档:
db.inventory.aggregate( [
{ $addFields: { instock: { $objectToArray: "$instock" } } },
{ $addFields: { instock: { $concatArrays: [ "$instock", [ { "k": "total", "v": { $sum: "$instock.v" } } ] ] } } } ,
{ $addFields: { instock: { $arrayToObject: "$instock" } } }
] )
操作返回以下结果:
{ "_id" : 1, "item" : "ABC1", "instock" : { "warehouse1" : 2500, "warehouse2" : 500, "total" : 3000 } }
{ "_id" : 2, "item" : "ABC2", "instock" : { "warehouse2" : 500, "warehouse3" : 200, "total" : 700 } }