gpt4 book ai didi

mongodb - 使用 upsert 更新,但仅当 db 中文档的日期字段小于更新的文档时才更新

转载 作者:IT老高 更新时间:2023-10-28 13:23:32 35 4
gpt4 key购买 nike

我在尝试为此提出逻辑时遇到了一些问题。所以,我想做的是:

  • 将一堆帖子批量更新到我的远程 MongoDB 实例但是
  • 如果更新,仅当远程集合上的 lastModified 字段小于我将要更新/插入的同一文档中的 lastModified 字段时才更新

基本上,我想更新我的文档列表,如果它们自上次更新以来被修改过。我可以想到两种蛮力方法来做到这一点......

首先,查询我的整个集合,尝试手动删除和替换符合条件的文档,添加新文档,然后在删除远程中的所有内容后将所有内容大量插入远程集合​​。

其次,查询每个项目,然后决定,如果远程有一个,我是否要更新它。在处理远程集合时,这似乎是一项非常艰巨的任务。

如果相关,我正在使用 NodeJS 环境,使用 mondodb npm 包进行数据库操作。

最佳答案

您可以使用 bulkWrite API 根据您指定的逻辑执行更新,因为它可以更好地处理此问题。

例如,以下代码段显示了如何执行此操作,假设您已经从 Web 服务中获得了更新远程集合所需的数据:

mongodb.connect(mongo_url, function(err, db) {
if(err) console.log(err);
else {
var mongo_remote_collection = db.collection("remote_collection_name");

/* data is from http call to an external service or ideally
place this within the service callback
*/
mongoUpsert(mongo_remote_collection, data, function() {
db.close();
})
}
})

function mongoUpsert(collection, data_array, cb) {
var ops = data_array.map(function(data) {
return {
"updateOne": {
"filter": {
"_id": data._id, // or any other filtering mechanism to identify a doc
"lastModified": { "$lt": data.lastModified }
},
"update": { "$set": data },
"upsert": true
}
};
});

collection.bulkWrite(ops, function(err, r) {
// do something with result
});

return cb(false);
}

如果来自外部服务的数据很大,那么考虑将写入分批发送到服务器 500 次,这样可以提高性能,因为您不会将每个请求都发送到服务器,而是每 500 个请求发送一次。

对于批量操作,MongoDB 强制使用 default internal limit每批处理 1000 次操作,因此选择 500 个文档是好的,因为您可以对批处理大小进行一些控制,而不是让 MongoDB 强加默认值,即对于大于 1000 个文档的较大操作。因此,对于第一种方法中的上述情况,可以一次写入所有数组,因为这很小,但 500 选择用于更大的数组。

var ops = [],
counter = 0;

data_array.forEach(function(data) {
ops.push({
"updateOne": {
"filter": {
"_id": data._id,
"lastModified": { "$lt": data.lastModified }
},
"update": { "$set": data },
"upsert": true
}
});
counter++;

if (counter % 500 === 0) {
collection.bulkWrite(ops, function(err, r) {
// do something with result
});
ops = [];
}
})

if (counter % 500 != 0) {
collection.bulkWrite(ops, function(err, r) {
// do something with result
}
}

关于mongodb - 使用 upsert 更新,但仅当 db 中文档的日期字段小于更新的文档时才更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41388908/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com