How to listen for changes to a MongoDB collection?

后端 未结 11 1631
不思量自难忘°
不思量自难忘° 2020-11-22 06:08

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 proce

11条回答
  •  滥情空心
    2020-11-22 06:55

    Since MongoDB 3.6 there will be a new notifications API called Change Streams which you can use for this. See this blog post for an example. Example from it:

    cursor = client.my_db.my_collection.changes([
        {'$match': {
            'operationType': {'$in': ['insert', 'replace']}
        }},
        {'$match': {
            'newDocument.n': {'$gte': 1}
        }}
    ])
    
    # Loops forever.
    for change in cursor:
        print(change['newDocument'])
    

提交回复
热议问题