demo_10_01 云数据库聚合_addFields_02

// 1. 数据库数据
// {
//  "vehicles": { // 集合(表名)
//      "data": [ // 数据
//          {
//              "_id": 1,
//              "type": "car",
//              "specs": {
//                  "doors": 4,
//                  "wheels": 4
//              }
//          },
//          {
//              "_id": 2,
//              "type": "motorcycle",
//              "specs": {
//                  "doors": 0,
//                  "wheels": 2
//              }
//          },
//          {
//              "_id": 3,
//              "type": "jet ski"
//          }
//      ]
//  }
// }

// 02. 聚合操作
‘use strict‘;
const db = uniCloud.database();
const $ = db.command.aggregate;
exports.main = async(event, context) => {
    /* 示例1:在嵌套记录里增加字段
    
    const msg = db.collection(‘vehicles‘).aggregate()
        .addFields({
            // 在已有的集合里添加字段,而不是创建新的集合
            ‘specs.fuel_type‘: ‘unleaded‘
        })
        .end();
        
    */

    // 示例2:设置字段值为另一个字段
    const msg = db.collection(‘vehicles‘).aggregate()
        // 添加了一个新字段
        .addFields({
            vehicle_type: ‘$type‘
        })
        .end()

    return msg;
};

// 聚合之后的返回值
/* 示例1:

{
    "affectedDocs": 3,
    "data": [{
        "_id": 1,
        "specs": {
            "doors": 4,
            "fuel_type": "unleaded",
            "wheels": 4
        },
        "type": "car"
    }, {
        "_id": 2,
        "specs": {
            "doors": 0,
            "fuel_type": "unleaded",
            "wheels": 2
        },
        "type": "motorcycle"
    }, {
        "_id": 3,
        "specs": {
            "fuel_type": "unleaded"
        },
        "type": "jet ski"
    }]
}

*/

/* 示例2:

{
    "affectedDocs": 3,
    "data": [{
        "_id": 1,
        "specs": {
            "doors": 4,
            "wheels": 4
        },
        "type": "car",
        "vehicle_type": "car"
    }, {
        "_id": 2,
        "specs": {
            "doors": 0,
            "wheels": 2
        },
        "type": "motorcycle",
        "vehicle_type": "motorcycle"
    }, {
        "_id": 3,
        "type": "jet ski",
        "vehicle_type": "jet ski"
    }]
}

*/

demo_10_01 云数据库聚合_addFields_02

上一篇:scrapy 基于管道持久化操作,分别存在本地和数据库


下一篇:redis-数据库