[英]Mongoose bulk insert or update documents
I am working on a node.js app, and I've been searching for a way around using the Model.save() function because I will want to save many documents at the same time, so it would be a waste of network and processing doing it one by one. 我正在开发一个node.js应用程序,并且一直在寻找一种使用Model.save()函数的方法,因为我想同时保存许多文档,因此这会浪费网络资源,处理一个接一个地做。
I found a way to bulk insert. 我找到了一种批量插入的方法。 However, my model has two properties that makes them unique, an ID and a HASH (I am getting this info from an API, so I believe I need these two informations to make a document unique), so, I wanted that if I get an already existing object it would be updated instead of inserted into the schema.
但是,我的模型有两个使它们唯一的属性,一个ID和一个HASH(我从API获取此信息,所以我相信我需要这两个信息才能使一个文档唯一),所以,如果我得到一个已经存在的对象,它将被更新而不是插入到架构中。
Is there any way to do that? 有什么办法吗? I was reading something about making concurrent calls to save the objects, using Q, however I still think this would generate an unwanted load on the Mongo server, wouldn't it?
我正在阅读有关使用Q进行并发调用以保存对象的内容,但是我仍然认为这会在Mongo服务器上产生不必要的负载,不是吗? Does Mongo or Mongoose have a method to bulk insert or update like it does with insert?
Mongo或Mongoose是否具有与insert一样的批量插入或更新方法?
Thanks in advance 提前致谢
I think you are looking for the Bulk.find(<query>).upsert().update(<update>)
function. 我认为您正在寻找
Bulk.find(<query>).upsert().update(<update>)
函数。
You can use it this way: 您可以通过以下方式使用它:
bulk = db.yourCollection.initializeUnorderedBulkOp();
for (<your for statement>) {
bulk.find({ID: <your id>, HASH: <your hash>}).upsert().update({<your update fields>});
}
bulk.execute(<your callback>)
For each document, it will look for a document matching the {ID: <your id>, HASH: {your hash}}
criteria. 对于每个文档,它将寻找一个符合
{ID: <your id>, HASH: {your hash}}
标准的文档。 Then: 然后:
{<your update fields>}
{<your update fields>}
更新该文档 As you need, it will not make a connection to the mongo server on each iteration of the for
loop. 根据需要,它不会在
for
循环的每次迭代中都连接到mongo服务器。 Instead a single call will be made on the bulk.execute()
line. 相反,将在
bulk.execute()
行上进行单个调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.