Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我在 Mongoid2 中有这个查询工作正常:
GlobalWord.collection.update({"_id" => "foo"}, {"$inc" => {:count => 1}}, :upsert => true)
如果找到GlobalWord带有 id 的foo,则将其计数更新一,否则它创建一个带有 idfoo且计数为 1 的文档。我在 mongoid3 中没有找到对应的。
GlobalWord
foo
编辑:我需要查询是原子的
我使用了 GlobalWord.create(:id => word).inc(:count, 1) 这似乎是原子的
我相信这应该有效:
GlobalWord.find("_id": "foo").upsert("$inc": {count: 1})
不过我没有测试它。我的手机上没有 MongoDB :)
来自文档和rdoc
GlobalWord.new(id: word).upsert("$inc" => {count: 1})