MongoDB as queue

想要把 MongoDB 裡的其中一個 collection 做為 queue, 讓多個 worker 存取來做事,可以利用 MongoDB 的 findAndModify。 findAndModify 是 atomic operation,執行的結果會回傳一個物件並且更新他的狀態。

例如現在有一個 collection 名為 keys, 裡面存著 {"id": id, "queued": false}

db.runCommand({"findAndModify": "keys", "query": {"queued": false}, "update": {"$set": {"queued": true}}})


就會回傳一個 document, 且將其 "queued" 設為 ture。因為是 atomic operation, 故可以保證每 worker 不會拿到相同的 document。

留言

這個網誌中的熱門文章

決定了!!!

P.S. I Love You

Tips: PPTP client on Openwrt