如何收听对MongoDB集合的更改? [英] How to listen for changes to a MongoDB collection?

查看:47
本文介绍了如何收听对MongoDB集合的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一种以MongoDB作为数据存储的后台作业队列系统.在催生工作者来处理作业之前,我如何监听" MongoDB集合中的插入内容?我是否需要每隔几秒钟轮询一次,以查看自上次以来是否有任何更改,或者我的脚本有什么方法可以等待插入发生?这是我正在从事的PHP项目,但是可以使用Ruby或与语言无关的方式随意回答.

I'm creating a sort of background job queue system with MongoDB as the data store. How can I "listen" for inserts to a MongoDB collection before spawning workers to process the job? Do I need to poll every few seconds to see if there are any changes from last time, or is there a way my script can wait for inserts to occur? This is a PHP project that I am working on, but feel free to answer in Ruby or language agnostic.

推荐答案

MongoDB具有所谓的 capped collections tailable cursors 允许MongoDB推送数据传递给听众.

MongoDB has what is called capped collections and tailable cursors that allows MongoDB to push data to the listeners.

A capped collection本质上是一个固定大小的集合,并且仅允许插入.这就是创建一个的样子:

A capped collection is essentially a collection that is a fixed size and only allows insertions. Here's what it would look like to create one:

db.createCollection("messages", { capped: true, size: 100000000 })

MongoDB可尾游标( Jonathan H. Wage的原始帖子)

Ruby

MongoDB Tailable cursors (original post by Jonathan H. Wage)

Ruby

coll = db.collection('my_collection')
cursor = Mongo::Cursor.new(coll, :tailable => true)
loop do
  if doc = cursor.next_document
    puts doc
  else
    sleep 1
  end
end

PHP

$mongo = new Mongo();
$db = $mongo->selectDB('my_db')
$coll = $db->selectCollection('my_collection');
$cursor = $coll->find()->tailable(true);
while (true) {
    if ($cursor->hasNext()) {
        $doc = $cursor->getNext();
        print_r($doc);
    } else {
        sleep(1);
    }
}

Python (通过 Robert Stewart)

from pymongo import Connection
import time

db = Connection().my_db
coll = db.my_collection
cursor = coll.find(tailable=True)
while cursor.alive:
    try:
        doc = cursor.next()
        print doc
    except StopIteration:
        time.sleep(1)

Perl (通过 Max )

use 5.010;

use strict;
use warnings;
use MongoDB;

my $db = MongoDB::Connection->new;
my $coll = $db->my_db->my_collection;
my $cursor = $coll->find->tailable(1);
for (;;)
{
    if (defined(my $doc = $cursor->next))
    {
        say $doc;
    }
    else
    {
        sleep 1;
    }
}

其他资源:

Ruby/Node.js指南创建一个侦听MongoDB封顶集合中的插入内容的应用程序.

这篇文章详细讨论了可尾光标.

使用可尾光标的PHP,Ruby,Python和Perl示例.

这篇关于如何收听对MongoDB集合的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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