有没有办法用一个查询插入或更新/替换MongoDB中的多个文档?
假设以下集合:
[
{_id: 1, text: "something"},
{_id: 4, text: "baz"}
]
现在我想添加多个文档,其中一些文档可能已经在集合中.如果这些文件已经在收集中,我想更新/替换它们.例如,我想插入以下文件:
[
{_id:1, text: "something else"},
{_id:2, text: "foo"},
{_id:3, text: "bar"}
]
查询应插入带有_id
2和3的文档.还应使用_id
1更新/替换文档.完成此过程后,集合应如下所示:
[
{_id:1, text: "something else"},
{_id:2, text: "foo"},
{_id:3, text: "bar"},
{_id:4, text: "baz"}
]
一种方法可能是使用insertMany
:
db.collection.insertMany(
[ {...}, {...}, {...} ],
{
ordered: false,
}
)
如果出现重复,该查询将发出一个writeErrors
,其中包含一个对象数组,其中包含未能插入的文档的索引.我可以浏览并更新它们.
But that process is cumbersome. Is there a way to insert or update/replace many documents in one query?