MongoDB将子文档的元素移动到另一个子文档

时间:2018-02-19 11:42:56

标签: javascript node.js mongodb mongoose aggregation-framework

我需要更改架构

const dataSchema = new Schema({
  trackingPrice: [{
    timeCheck: { type: Date, default: Date.now },
    lowestPrice: Number,
    salePrice: Number,
    saleRank: Number
  }]
})

到这个

const dataSchema = new Schema({
  trackingPrice: [{
    timeCheck: { type: Date, default: Date.now },
    lowestPrice: Number,
    salePrice: Number
  }],
  trackingRank: [{
    timeCheck: { type: Date, default: Date.now },
    saleRank: Number
  }]
})

如何在文档下将数据从一个数据传输到另一个,然后删除“saleRank”?

2 个答案:

答案 0 :(得分:0)

我看到的最好的方法是找到所有这些,并预先创建一个新的

我正在使用猫鼬

normalize.css

答案 1 :(得分:0)

基于此 very good answer ,您的案例中的光标将来自运行汇总管道:

const pipeline = [
    {
        "$project": {
            "trackingPrice": {
                "$map": {
                    "input": "$trackingPrice",
                    "as": "el",
                    "in": { 
                        "timeCheck": "$$el.timeCheck",
                        "lowestPrice": "$$el.timeCheck",
                        "salePrice": "$$el.salePrice"
                    }
                }
            },
            "trackingRank": {
                "$map": {
                    "input": "$trackingPrice",
                    "as": "el",
                    "in": { 
                        "timeCheck": "$$el.timeCheck",
                        "saleRank": "$$el.saleRank"
                    }
                }
            }
        }
    }
];

const cursor = Data.aggregate(pipeline).exec();

运行批量更新:

let bulkUpdateOps = [];

cursor.then(results => {
    results.forEach(doc => {
        const { _id, trackingPrice, trackingRank } = doc;
        bulkUpdateOps.push({
            "updateOne": {
               "filter": { _id },
               "update": { "$set": { trackingPrice, trackingRank } },
               "upsert": true
            }
        });
    }); 

    if (bulkUpdateOps.length === 1000) {
        bulkUpdateOps = [];
        return Data.bulkWrite(bulkUpdateOps);           
    }       

}).then(console.log).catch(console.error);

if (bulkUpdateOps.length > 0) {
    Data.bulkWrite(bulkUpdateOps).then(console.log).catch(console.error);
}