Reputation: 126357
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"}, ...]
Upvotes: 2
Views: 3709
Reputation: 118271
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"}]
Upvotes: 5
Reputation: 126357
I found the complete solution.
mongo_db['users'].find().to_a.each do |u|
u['id'] = u.delete '_id'
end.to_json
Upvotes: 4