MongoDB聚合运算符:$arrayToObject

MongoDb聚合运算符$arrayToObject可以将一个数组转换为文档。注意只有两种数组才可以转换为文档,参见$arrayToObject使用

语法

{ $arrayToObject: <expression> }

必须是数组或能够被解析为数组的表达式,而且数组元素要么是只有两个元素的数组,要么是包含kv两个字段的文档数组。

使用

注意,不是所有的数组表达式都能转换为文档,只有下面两种数组才可以进行转换:

  1. 只有两个元素的数组,第一个元素为字段名,第二个元素为字段值:

    [ [ [ "item", "abc123" ], [ "qty", 25 ] ] ]
    
  2. 包含两个字段的文档数组,一个字段是k一个字段是v

    1. 字段k包含了字段名
    2. 字段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" }

举例

$arrayToObject

集合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 ] ] }

下面的聚合管道使用$arrayToObjectdimensions数组字段转换为文档:

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 } }

objectToAarry和$arrayToObject

集合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 } }

你可能感兴趣的:(mongodb,mongodb,数据库)