在 mongodb shell 中使用异步循环来更新许多文档
Using async loop in mongodb shell for updating many documents
我在 MongoDB shell 中的以下查询只有当数组的大小变大时才会出现问题,例如,超过 100 个元素。
newPointArray --> is an array with 500 elements
newPointArray.forEach(function(newDoc){
//update the mongodb properties for each doc
db.getCollection('me_all_test')
.update({ '_id': newDoc._id },
{ $set: { "properties": newDoc.properties } },
{ upsert: true });
})
有人可以指导我如何通过使用异步循环或承诺或... 运行 IN MongoDB SHELL 查询更大的数组吗?
提前致谢
与其进行单独的 .update()
,不如使用 .bulkWrite()
操作。这应该可以减少要求 mongo 执行多个单独操作的开销。这是假设您正在进行一般操作。我不清楚 newPointArray
是否总是不存在的新点。
鉴于您的示例,我相信您的脚本会模仿以下内容:
// I'm assuming this is your array (but truncated)
let newPointArray = [
{
_id: "1",
properties: {
foo: "bar"
}
},
{
_id: "2",
properties: {
foo: "buzz"
}
}
// Whatever other points you have in your array
];
db
.getCollection("me_all_test")
.bulkWrite(newPointArray
// Map your array to a query bulkWrite understands
.map(point => {
return {
updateOne: {
filter: {
_id: point._id
},
update: {
$set: {
properties: point.properties
}
},
upsert: true
}
};
}));
您可能还需要考虑在操作中将 ordered
设置为 false,这也可能会提高性能。那看起来像这样:
db
.getCollection("me_all_test")
.bulkWrite([SOME_ARRAY_SIMILAR_TO_ABOVE_EXAMPLE], {
ordered: false
});
我在 MongoDB shell 中的以下查询只有当数组的大小变大时才会出现问题,例如,超过 100 个元素。
newPointArray --> is an array with 500 elements
newPointArray.forEach(function(newDoc){
//update the mongodb properties for each doc
db.getCollection('me_all_test')
.update({ '_id': newDoc._id },
{ $set: { "properties": newDoc.properties } },
{ upsert: true });
})
有人可以指导我如何通过使用异步循环或承诺或... 运行 IN MongoDB SHELL 查询更大的数组吗?
提前致谢
与其进行单独的 .update()
,不如使用 .bulkWrite()
操作。这应该可以减少要求 mongo 执行多个单独操作的开销。这是假设您正在进行一般操作。我不清楚 newPointArray
是否总是不存在的新点。
鉴于您的示例,我相信您的脚本会模仿以下内容:
// I'm assuming this is your array (but truncated)
let newPointArray = [
{
_id: "1",
properties: {
foo: "bar"
}
},
{
_id: "2",
properties: {
foo: "buzz"
}
}
// Whatever other points you have in your array
];
db
.getCollection("me_all_test")
.bulkWrite(newPointArray
// Map your array to a query bulkWrite understands
.map(point => {
return {
updateOne: {
filter: {
_id: point._id
},
update: {
$set: {
properties: point.properties
}
},
upsert: true
}
};
}));
您可能还需要考虑在操作中将 ordered
设置为 false,这也可能会提高性能。那看起来像这样:
db
.getCollection("me_all_test")
.bulkWrite([SOME_ARRAY_SIMILAR_TO_ABOVE_EXAMPLE], {
ordered: false
});