Bắt đầu từ phiên bản 3.4, chúng ta có thể sử dụng toán tử đường ống $addFields
hợp này mà không xử lý phía khách hàng mà là hiệu quả nhất đường.
db.collection.aggregate(
[
{ "$addFields": { "field2": "$field1" }},
{ "$out": "collection" }
]
)
Trước khi phiên bản 3.4 chúng ta cần phải lặp đối tượng Cursor
và sử dụng $set
hành thêm lĩnh vực mới với giá trị "field1" hiện có. Bạn cần phải làm điều này bằng cách sử dụng "số lượng lớn" hoạt động cho hiệu quả tối đa.
MongoDB 3.2 không dùng Bulk()
và associated methods, do đó từ 3,2 trở lên bạn cần sử dụng phương pháp bulkWrite
.
var requests = [];
db.collection.find({}, { 'field1': 1 }).snapshot().forEach(document => {
requests.push({
'updateOne': {
'filter': { '_id': document._id },
'update': { '$set': { 'field2': document.field1 } }
}
});
if (requests.length === 1000) {
//Execute per 1000 operations and re-init
db.collection.bulkWrite(requests);
requests = [];
}
});
if(requests.length > 0) {
db.collection.bulkWrite(requests);
}
Từ phiên bản 2,6-3,0 bạn có thể sử dụng Bulk
API.
var bulk = db.collection.initializeUnorderedBulOp();
var count = 0;
db.collection.find({}, { 'field1': 1 }).snapshot().forEach(function(document) {
bulk.find({ '_id': document._id }).updateOne({
'$set': { 'field2': document.field1 }
});
count++;
if(count%1000 === 0) {
// Excecute per 1000 operations and re-init
bulk.execute();
bulk = db.collection.initializeUnorderedBulkOp();
}
})
// clean up queues
if(count > 0) {
bulk.execute();
}
câu hỏi Rất tương tự: http://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field/ –