AggregateCommand.objectToArray(value: Expression<object>): Object

支持端:小程序 2.7.4, 云函数 0.8.1, Web

聚合操作符。将一个对象转换为数组。方法把对象的每个键值对都变成输出数组的一个元素,元素形如 { k: &lt;key&gt;, v: &lt;value&gt; }

参数

value: Expression<object>

返回值

Object

API 说明

语法如下:

  1. db.command.aggregate.objectToArray(<object>)

示例代码

假设集合 items 有如下记录:

  1. { "_id": 1, "attributes": { "color": "red", "price": 150 } }
  2. { "_id": 2, "attributes": { "color": "blue", "price": 50 } }
  3. { "_id": 3, "attributes": { "color": "yellow", "price": 10 } }
  1. const $ = db.command.aggregate
  2. db.collection('items').aggregate()
  3. .project({
  4. array: $.objectToArray('$attributes')
  5. })
  6. .end()

返回结果如下:

  1. { "_id": 1, "array": [{ "k": "color", "v": "red" }, { "k": "price", "v": 150 }] }
  2. { "_id": 2, "array": [{ "k": "color", "v": "blue" }, { "k": "price", "v": 50 }] }
  3. { "_id": 3, "array": [{ "k": "color", "v": "yellow" }, { "k": "price", "v": 10 }] }