How do I rename the _id
keys to id
in an array of MongoDB documents?
如何在MongoDB文档数组中将_id键重命名为id?
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 个解决方案
#1
3
I found the complete solution.
我找到了完整的解决方案。
mongo_db['users'].find().to_a.each do |u|
u['id'] = u.delete '_id'
end.to_json
#2
0
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"}]
#1
3
I found the complete solution.
我找到了完整的解决方案。
mongo_db['users'].find().to_a.each do |u|
u['id'] = u.delete '_id'
end.to_json
#2
0
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"}]