2

How do I rename the _id keys to id in an array of MongoDB documents?

So, I want to make this:

[{"_id"=>"1", "name"=>"Matt"}, {"_id"=>"2", "name"=>"John"}, ...]

into this:

[{"id"=>"1", "name"=>"Matt"}, {"id"=>"2", "name"=>"John"}, ...]

2 Answers 2

5
ar = [{"_id"=>"1", "name"=>"Matt"}, {"_id"=>"2", "name"=>"John"}]
ar.each{|h| h.store('id',h.delete('_id'))}
ar # => [{"name"=>"Matt", "id"=>"1"}, {"name"=>"John", "id"=>"2"}]

If you don't want to modify the original array do as below:

ar = [{"_id"=>"1", "name"=>"Matt"}, {"_id"=>"2", "name"=>"John"}]
ar.map{|h| {"id"=>h['_id'], "name"=>h['name']} }
# => [{"id"=>"1", "name"=>"Matt"}, {"id"=>"2", "name"=>"John"}]
Sign up to request clarification or add additional context in comments.

Comments

4

I found the complete solution.

mongo_db['users'].find().to_a.each do |u|
  u['id'] = u.delete '_id'
end.to_json

1 Comment

This works perfectly well, however, it is really not that obvious (at a glance) what is being done, so might confuse another coder. Making this a helper method, or at least adding a comment, would make it better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.