1

我想将文档中的价格信息复制到prices[]数组中。

var entitiesCol = db.getCollection('entities');
entitiesCol.find({"type": "item"}).forEach(function(item){
    item.prices = [ {
        "value": item.price
    }];
    entitiesCol.save(item);
});

时间太长,有些字段没有更新。

我在服务器端使用猫鼬,我也可以使用它。

我能为此做些什么?

4

1 回答 1

1

在 mongo shell 中,您可以使用该bulkWrite()方法快速高效地进行更新。考虑以下示例:

var entitiesCol = db.getCollection('entities'),
    counter = 0,
    ops = [];
entitiesCol.find({
    "type": "item",
    "prices.0": { "$exists": false }
}).snapshot().forEach(function(item){
    ops.push({
        "updateOne": {
            "filter": { "_id": item._id },
            "update": { 
                "$push": {
                    "prices": { "value": item.price }
                }
            }
        }
    });
    counter++;

    if (counter % 500 === 0) {
        entitiesCol.bulkWrite(ops);
        ops = [];
    }
})

if (counter % 500 !== 0) 
    entitiesCol.bulkWrite(ops);

counter如果您的集合很大,上面的变量可以有效地管理您的批量更新。它允许您批量更新操作并以 500 个批次将写入发送到服务器,这可以为您提供更好的性能,因为您不会将每个请求都发送到服务器,而是每 500 个请求发送一次。

对于批量操作,MongoDB 规定了每批1000 次操作的默认内部限制,因此从某种意义上说,选择 500 个文档是好的,因为您可以对批量大小进行一些控制,而不是让 MongoDB 强加默认值,即对于规模较大的操作> 1000 个文档。

于 2016-12-30T13:58:00.100 回答