我测试了 updateMany。
测试1:
使用 updateMany (pull) 更新 40K 文档,在执行过程中,突然关闭 db,然后一些节点通过(数据被拉出),一些失败(数据未在树中的某些级别 5 节点中拉出),重新启动 db 并再次运行 updateMany ,所有通过并且所有数据现在都是正确的。
测试2:
在字段上创建唯一索引,插入一些数据,在updateMany方法中,一些文档会因为唯一键冲突而失败。
我的 test2 结果是:零文档已更新。
function insertData() {
const dataSource = app.models.Entity.getDataSource();
return new Promise((resolve, reject) => {
dataSource.connector.connect((err, db) => {
if (err) {
reject(new Error('.... error'));
return;
}
const entityCollection = db.collection('Entity');
// Create index
entityCollection.createIndex({ age: 1 }, { unique: true })
.then(() => {
// Insert data
const data = [
{
id: uuid.v4(),
age: 1,
type: 'test',
},
{
id: uuid.v4(),
age: 2,
type: 'test',
},
{
id: uuid.v4(),
age: 3,
type: 'test',
},
{
id: uuid.v4(),
age: 4,
type: 'test',
},
{
id: uuid.v4(),
age: 5,
type: 'test',
},
{
id: uuid.v4(),
age: 6,
type: 'test',
},
];
return insertData(data);
})
.then(() => {
resolve();
})
.catch((err2) => {
reject(err2);
});
});
});
}
function updateAge() {
const dataSource = app.models.Entity.getDataSource();
return new Promise((resolve, reject) => {
dataSource.connector.connect((err, db) => {
if (err) {
reject(new Error('...error'));
return;
}
const entityCollection = db.collection('Entity');
entityCollection.updateMany(
{ age: { $gt: 0 } },
{ $mul: { age: 2 } },
).then(() => {
resolve();
})
.catch((err2) => {
logger.error(`ERROR is ${err2}`);
reject(err2);
});
});
});
}
测试结果是:零个文档被更新。
"msg":"ERROR is MongoError: E11000 duplicate key error collection: content-base.Entity index: age_1 dup key: { : 2 }","v":1}
1) updateMany 测试
0 通过 (114ms)
1 次失败