在MongoDB中插入或更新许多文档 [英] Insert or update many documents in MongoDB

查看:64
本文介绍了在MongoDB中插入或更新许多文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过单个查询在MongoDB中插入或更新/替换多个文档?

Is there a way to insert or update/replace multiple documents in MongoDB with a single query?

假设以下集合:

[
    {_id: 1, text: "something"},
    {_id: 4, text: "baz"}
]

现在,我想添加多个文档,其中某些文档可能已经在集合中.如果文档已在集合中,我想对其进行更新/替换.例如,我要插入以下文档:

Now I would like to add multiple documents of which some might already be in the collection. If the documents are already in the collection, I would like to update/replace them. For example, I would like to insert the following documents:

[
    {_id:1, text: "something else"},
    {_id:2, text: "foo"},
    {_id:3, text: "bar"}
]

查询应插入带有_id 2和3的文档.它还应该带有_id 1的文档更新/替换.在此过程之后,集合应如下所示:

The query should insert the documents with _id 2 and 3. It should also update/replace the document with _id 1. After the process, the collection should look as follows:

[
    {_id:1, text: "something else"},
    {_id:2, text: "foo"},
    {_id:3, text: "bar"},
    {_id:4, text: "baz"}
]

一种方法可能是使用 insertMany :

One approach might be to use insertMany:

db.collection.insertMany(
   [ {...}, {...}, {...} ],
   {
      ordered: false,
   }
)

如果出现重复,该查询将发出一个writeErrors,该writeErrors包含一个对象数组,其中包含未能插入的文档的索引.我可以浏览它们并更新它们.

If duplicates occur, that query will emit a writeErrors containing an array of objects containing the indexes of the documents that failed to insert. I could go through them and update them instead.

但是该过程很麻烦.有没有一种方法可以在一个查询中插入或更新/替换许多文档?

But that process is cumbersome. Is there a way to insert or update/replace many documents in one query?

推荐答案

如所述

As said here, to do what you need you can put something like this in

script.js

script.js

( *警告:未经测试的代码)

use YOUR_DB
var bulk = db.collection.initializeUnorderedBulkOp();
bulk.find( { _id : 1 } ).upsert().update( { $set: { "text": "something else" } } );
bulk.find( { _id : 4 } ).upsert().update( { $set: { "text": "baz" } } );
bulk.find( { _id : 99 } ).upsert().update( { $set: { "text": "mrga" } } );
bulk.execute();

并使用

mongo< script.js

mongo < script.js

我必须这样做,因为由于限制,我尝试更新/插入1000多个文档的任何操作均不起作用.

I had to do it this way as anything I tried for updating/inserting more than 1000 documents didn't work because of the limit.

写入命令最多可以接受1000个操作. mongo shell中的Bulk()操作和驱动程序中的类似方法没有此限制.

Write commands can accept no more than 1000 operations. The Bulk() operations in the mongo shell and comparable methods in the drivers do not have this limit.

这篇关于在MongoDB中插入或更新许多文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆