用 ruby 保存/更新 (Moped) BSON::Document

save / update a (Moped) BSON::Document with ruby

我尝试了很多方法来更新现有的 bson 文档,但它在我的 mongodb:

中从未改变
col = db["collection"]
col.insert({"ben": 1})
doc = col.find().to_a.first
# => {"_id"=>BSON::ObjectId('556c7f1b167e70640070a4d9'), "ben"=>1}

第一次尝试更新:

doc.merge!({"ben": 5, "ams": 6})
col.find().to_a.first
# => {"_id"=>BSON::ObjectId('556c7f1b167e70640070a4d9'), "ben"=>1}

第二次尝试更新:

doc.update({"ben": 5, "ams": 6})
col.find().to_a.first
# => {"_id"=>BSON::ObjectId('556c7f1b167e70640070a4d9'), "ben"=>1}

第三次尝试...

doc["ben"] = 5
doc["ams"] = 6
doc.save
# NoMethodError: undefined method `save' for #<BSON::Document:0x00000003f284d0>

如您所见,上述 none 对我有用。我无法通过 google 搜索找到任何其他建议。你知道更新我的文档的方法吗?可能吗?

一旦你这样做:

col.find().to_a
#          ^^^^

您正在使用一个简单的 Ruby 哈希数组,该数组与数据库没有连接。所以当你说:

doc.update({"ben": 5, "ams": 6})

您正在呼叫 Hash#update. If you want to update something, you'd call update on what find returns:

col.find.update(:$set => { 'ben' => 5, 'ams' => 6 })

或者如果您想替换整个文档:

col.find.update('ben' => 5, 'ams' => 6)

您通常会告诉 find 您当然想要哪个特定文件。

注意 update 只更新它找到的第一个匹配文档,如果你想更新所有匹配的文档,那么你可以使用 update_all.