如何将 Mongo 游标转换为嵌套哈希?
我对 Ruby 和 Mongo 都是新手,有 C# 和 SQL Server 背景。我有一个简单的文档,如下所示:
db = Mongo::Connection.new.db("crm")
coll = db["persons"]
coll.find().each { |row| puts row.inspect }
-- 输出:
{"_id"=>BSON::ObjectId('4cd6d8db1d41c81731000001'), "company"=>"Acme Ltd", "name"=>"John Smith", "id"=>"1"}
{"_id"=>BSON::ObjectId('4cd6d8db1d41c81731000002'), "company"=>"Widget Co", "name"=>"Jane Smith", "id"=>"2"}
我需要将此游标对象转换为散列的嵌套散列,如下所示:
@result = {
"1"=>{"name"=>"John Smith", "company"=>"Acme Ltd"},
"2"=>{"name"=>"Jane Smith", "company"=>"Widget Co"}
}
“1”和“2”是游标中的“id”值。
有没有一种很酷的 Ruby 方法来完成这个任务?
I am new to both Ruby and Mongo, coming from a C# and SQL Server background. I have a simple document which looks like:
db = Mongo::Connection.new.db("crm")
coll = db["persons"]
coll.find().each { |row| puts row.inspect }
-- Outputs:
{"_id"=>BSON::ObjectId('4cd6d8db1d41c81731000001'), "company"=>"Acme Ltd", "name"=>"John Smith", "id"=>"1"}
{"_id"=>BSON::ObjectId('4cd6d8db1d41c81731000002'), "company"=>"Widget Co", "name"=>"Jane Smith", "id"=>"2"}
I need to transform this cursor object into a nested hash of hashes that looks like this:
@result = {
"1"=>{"name"=>"John Smith", "company"=>"Acme Ltd"},
"2"=>{"name"=>"Jane Smith", "company"=>"Widget Co"}
}
The "1" and "2" are the "id" values from the cursor.
Is there a cool Ruby way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请将行更改
为
如果要删除 _id, add row.delete('_id');在将其分配给结果变量之前。
希望这会有所帮助。
change the line
to
if you want to delete the _id add row.delete('_id'); before assigning it to the result variable.
hope this will help.