Mongodb来自多个进程的查询; 如何实现primefaces性?
我有一个mongodb数据库,其中有多个节点进程读取和写入文档。 我想知道如何才能做到这一点,所以一次只能有一个进程可以在文档上工作。 (某种forms的locking)在进程完成更新该条目后释放。
我的应用程序应该做以下几点:
- 用光标逐个浏览每个条目。
-
(locking条目,使其他进程无法使用它)
-
从第三方网站获取信息。
- 计算新信息并更新条目。
- (解锁文件)
同样在解锁文档之后,其他进程将不需要更新它几个小时。
后来我想设置多个mongodb集群,以便减less数据库的负载。 所以解决scheme应该适用于单个和多个数据库服务器。 或者至less使用多个mongo服务器。
一个不涉及锁的优雅解决scheme是:
-
将
version
属性添加到您的文档。 -
更新文档时,增加
version
属性。 -
更新文档时,在查找查询中包含上次读取的
version
。 如果您的文档已在其他地方更新,查找查询将不会产生任何结果,您的更新将失败。 -
如果更新失败,则可以重试该操作。
过去我用这个模式取得了很大的成功。
例
试想一下你有一个文档{_id: 123, version: 1}
。
想象一下,你现在有3个Mongo客户端做db.collection.findAndModify({ query: {_id: 123, version: 1}, update: { $inc: 1 }});
,同时。
第一次更新将适用,其余将失败。 为什么? 因为现在version
是2
,并且query
包括version: 1
。
每个MongoDB文档 : isolated: Prevents a write operation that affects multiple documents from yielding to other reads or writes once the first document is written... $isolated operator causes write operations to acquire an exclusive lock on the collection...will make WiredTiger single-threaded for the duration of the operation.
因此,如果您要更新多个文档,您可以先从第三方API获取数据,然后将信息parsing为数组,然后在Mongo shell中使用这样的内容:
db.foo.update( { status : "A" , $isolated : 1 }, { $set: { < your key >: < your info >}}, //use the info in your array { multi: true } )
或者,如果您必须逐一更新文档,则可以使用MongoDB的节点驱动程序的findAndModify()或updateOne()。 请注意,根据MongoDB文档 '修改单个文档时,findAndModify()和update()方法primefaces更新文档。
一个一个的例子:首先用NodeJS驱动程序连接到Mongod ,然后使用NodeJS的Request模块连接到第三部分的API,例如获取和parsing数据,然后使用数据修改你的文档 ,如下所示:
var request = require('request'); var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { var collection = db.collection('simple_query'); collection.find().forEach( function(doc) { request('http://www.google.com', function(error, response, body) { console.log('body:', body); // parse body for your info collection.findAndModify({ <query based on your doc> }, { $set: { < your key >: < your info > } }) }); }, function(err) { }); });