开发者

How do I transform a Mongo cursor into nested hash?

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"=>"Wid开发者_Python百科get Co"}
}

The "1" and "2" are the "id" values from the cursor.

Is there a cool Ruby way to accomplish this?


change the line

coll.find().each { |row| puts row.inspect }

to

@result = {}
coll.find().each { |row| id = row.delete('id'); @result["#{id}"] = row }
puts @result.inspect

if you want to delete the _id add row.delete('_id'); before assigning it to the result variable.

hope this will help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜