MongoDB 3.4 版本中的最佳方式。
这个版本的mongod
提供了$split运算符,当然,它会分割字符串,如图所示here.
然后我们使用以下方法将新计算的值分配给变量$let变量运算符。然后可以在以下位置使用新值in表达式使用以下命令返回“姓名”和“年龄”值$arrayElemAt运算符返回指定索引处的元素;0
对于第一个元素和-1
对于最后一个元素。
请注意,在in表达式我们需要拆分最后一个元素才能返回整数字符串。
最后我们需要迭代Cursor
对象并使用将整数字符串转换为数字Number or parseInt并使用批量操作和bulkWrite()方法$set这些字段的值可实现最大效率。
let requests = [];
db.coll.aggregate(
[
{ "$project": {
"person": {
"$let": {
"vars": {
"infos": { "$split": [ "$person", "," ] }
},
"in": {
"name": { "$arrayElemAt": [ "$$infos", 0 ] },
"age": {
"$arrayElemAt": [
{ "$split": [
{ "$arrayElemAt": [ "$$infos", -1 ] },
" "
]},
-1
]
}
}
}
}
}}
]
).forEach(document => {
requests.push({
"updateOne": {
"filter": { "_id": document._id },
"update": {
"$set": {
"name": document.person.name,
"age": Number(document.person.age)
},
"$unset": { "person": " " }
}
}
});
if ( requests.length === 500 ) {
// Execute per 500 ops and re-init
db.coll.bulkWrite(requests);
requests = [];
}}
);
// Clean up queues
if(requests.length > 0) {
db.coll.bulkWrite(requests);
}
MongoDB 3.2 或更高版本。
MongoDB 3.2 弃用旧版本Bulk()API及其相关methods并提供bulkWrite()
方法,但它没有提供$split
运算符,所以我们这里唯一的选择是使用mapReduce()方法来转换我们的数据,然后使用批量操作更新集合。
var mapFunction = function() {
var person = {},
infos = this.person.split(/[,\s]+/);
person["name"] = infos[0];
person["age"] = infos[2];
emit(this._id, person);
};
var results = db.coll.mapReduce(
mapFunction,
function(key, val) {},
{ "out": { "inline": 1 } }
)["results"];
results.forEach(document => {
requests.push({
"updateOne": {
"filter": { "_id": document._id },
"update": {
"$set": {
"name": document.value.name,
"age": Number(document.value.age)
},
"$unset": { "person": " " }
}
}
});
if ( requests.length === 500 ) {
// Execute per 500 operations and re-init
db.coll.bulkWrite(requests);
requests = [];
}}
);
// Clean up queues
if(requests.length > 0) {
db.coll.bulkWrite(requests);
}
MongoDB 版本 2.6 或 3.0。
我们需要使用现在已弃用的Bulk API.
var bulkOp = db.coll.initializeUnorderedBulkOp();
var count = 0;
results.forEach(function(document) {
bulkOp.find({ "_id": document._id}).updateOne(
{
"$set": {
"name": document.value.name,
"age": Number(document.value.age)
},
"$unset": { "person": " " }
}
);
count++;
if (count === 500 ) {
// Execute per 500 operations and re-init
bulkOp.execute();
bulkOp = db.coll.initializeUnorderedBulkOp();
}
});
// clean up queues
if (count > 0 ) {
bulkOp.execute();
}