mongodb - MongoDB - 在对多个文档进行“如果不存在则插入”操作后获取插入和现有文档的 ID
问题描述
如果它们尚不存在,我必须插入多个文档,但重要的是,在查询结果中,我需要同时拥有已插入和已存在项目的 ID。
我正在尝试以下bulkWrite
操作:
// external_id is a unique id other than the mongo _id
let items = [
{external_id: 123, name: "John"},
{external_id: 456, name: "Mike"},
{external_id: 789, name: "Joseph"}
];
db.collection("my_collection")
.bulkWrite(
items.map((item) => {
return {
updateOne: {
filter: { external_id: item.external_id },
update: { $setOnInsert: item},
upsert: true,
},
};
})
);
问题是BulkWriteResult
只返回_id
中插入的项目upsertedIds
,而现有项目只返回nMatched
数字。
我考虑的另一个解决方案是(1)find
在一个id数组上创建一个,(2)检查已经存在的结果,(3)然后insertMany
是新的:
let ids = [123, 456, 789];
let items = [
{external_id: 123, name: "John"},
{external_id: 456, name: "Mike"},
{external_id: 789, name: "Joseph"}
];
// STEP 1: Find alredy existings items
db.collection("my_collection")
.find({ external_id: { $in: ids } })
.toArray(function (err, existingItems) {
// If John already exist
// existingItems = [{_id: ObjectId, external_id: 123, name: "John"}]
// STEP 2: Check which item has to be created
let itemsToBeCreated = items.filter((item) =>
!existingItems.some((ex) => ex.external_id === item.external_id)
);
// STEP 3: Insert new items
db.collection("my_collection")
.insertMany(itemsToBeCreated, function (err, result) {
// FINALLY HERE I GET ALL THE IDs OF THE EXISTING AND INSERTED ITEMS
});
});
使用此解决方案,我关心性能,因为这些操作每天针对 10 个项目执行 100K 次,并且大约 90% 的项目是新的。所以 900K 新项目和 100K 已经存在。
我想知道是否有更好的方法来实现这一点。
提前致谢
解决方案
推荐阅读
- c# - 仅使用循环更改硬币,C# 中没有数组
- python - Dask 客户端 + read_sql_table:distributed.protocol.core - 严重 - 无法序列化
- sql - 我们如何在 SQL 存储过程中捕获“near-misses”,该存储过程使用连接逻辑在 2 个表之间找到匹配项?
- javascript - Next.js:嵌套动态路由数据结构错误的getStaticPaths
- reactjs - 未指定任何元素来初始化 Windows 上的 PerfectScrollbar
- html - 如何从 textarea 中的文本输入中删除下划线?
- java - Firebase 通过电子邮件注册并通过 - 如何向用户添加其他详细信息
- c - 从 'char' 到 'char' 的无效转换 [-fpermissive] 16 | A[++顶部] = x; | ^ | | | 字符*
- asp.net - ASP.Net Url Rewrite Url 重定向过多
- html - 如何将 Emoji 集成到 link_to