ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]
mongo (2.0.4)
我需要帮助来查询带有其gem的MongoDB数据库并更新适当的字段。
编辑:我正在尝试遍历Mongo数据库的文档,下拉那些文档中特定字段的值,并稍后在脚本中更新它们。
目标在数据库中查询字段partner_id
为“伙伴”和字段state
为“已设置”的文档,并仅返回_id
andconfig
字段下的值。
使用新生成的每个文档config
字段的密码更新数据库。
我已经不知所措了,因为我已经看到了大约六种不同的语法编写方式,而且除非我已经知道如何做这些文档,否则文档对他们没有多大帮助。任何帮助将不胜感激!
#!/usr/bin/env ruby
require 'json'
require 'net/http'
require 'mongo'
# Fetch the addons database URI and connect.
db_uri = ENV['DATABASE_URI']
client = Mongo::Client.new(db_uri)
# Connect to the needed collection and pull down each document to be looped over individually.
# **Having trouble getting this to work. The result is just '= []' - don't know what I'm doing wrong.
client[:collection].find("partner_id" => "partner", "state" => "provisioned", :fields => ["_id", "config"]).each {
# Need something here to pull down the values from each document's '_id' and 'config' fields and assign them to variables.
user_id =
user_config =
user_config = JSON.parse(user_config)
# ...generating password and updating other database...
# Convert the Hash of the user's new configuration into JSON, and update the original database with it.
# Not sure if any of this is correct. When querying to check, the database doesn't seem to be updated.
user_config = user_config.to_json
client[:collection].update(
{"_id" => user_id},
{'$set' => {
"config" => user_config
}
}
)
}
end
return
您找不到任何东西,因为:
:fields => ["_id", "config"]
的参数find
未指定您想要的字段,find
只是将其视为要查找的第三个文档字段。您的文档可能没有名为field
的字段,该字段的值是这些字符串的数组,因此查询无提示地根本找不到任何内容。
如果要限制查询,则需要使用projection
:
client[:collection].find("partner_id" => "partner", "state" => "provisioned")
.projection('_id' => 1, 'config' => 1)
.each { |doc| ... }
然后在该each
区块内doc
将是一个哈希,因此您可以说:
user_id = doc['user_id']
user_config = doc['user_config']
如果我正确阅读了您的代码,则该代码user_config
应该已经是Hash,因此您可能不需要自己解析它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句