我正在创建一种后台作业(job)队列系统,使用MongoDB作为数据存储.在生成处理作业(job)的工作人员之前,如何"侦听"MongoDB集合的插入?

我是否需要每隔几秒钟进行一次轮询,以查看与上次相比是否有任何更改,或者我的脚本是否有办法等待插入发生?

这是我正在做的一个PHP项目,但请随意用Ruby或不可知语言回答.

推荐答案

MongoDB有所谓的capped collectionstailable cursors,允许MongoDB将数据推送到监听器.

capped collection基本上是一个固定大小的集合,只允许插入.下面是创建一个的样子:

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

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 Tutorial which walks you through creating an application that listens to inserts in a MongoDB capped collection.

An article talking about tailable cursors in more detail.

PHP, Ruby, Python, and Perl examples of using tailable cursors.

Mongodb相关问答推荐

更新查询mongoose 中的礼宾更新字段

MongoDB:删除键上有条件的对象元素

查找/查找单个深度嵌套文档的多个集合

数组相等条件返回的文档多于与相等匹配的文档:MongoDB

在mongdob中按子文档筛选不起作用

使用特定关键字和邻近度进行查询和过滤

Mongodb Timeseries / Golang - ['timestamp' 必须存在并包含有效的 BSON UTC 日期时间值]

Mongo 聚合将 $sort 与 $geoNear 结合使用

如何更新mongo中列表最后一个对象的属性

MongoDB 列表 - 获取每第 N 个元素

如何将 json 字符串编组到 bson 文档以写入 MongoDB?

MongoDB 的 Java 语法

带有 mongodb 和 nodejs 的实时 Web 应用程序

如何在 $lookup Mongodb 的 LocalField 中将字符串转换为 objectId

Clojure 和 NoSQL 数据库

NodeJS中的密码重置

如何使用服务器实例指定 mongodb 用户名和密码?

MongoDB mongoexport 查询

mongoosefind()不返回结果

如何使用户的邮箱在 mongoDB 中唯一?