如何重命名MongoDB 文档数组中的_id
键?id
所以,我想做这个:
[{"_id"=>"1", "name"=>"Matt"}, {"_id"=>"2", "name"=>"John"}, ...]
进入这个:
[{"id"=>"1", "name"=>"Matt"}, {"id"=>"2", "name"=>"John"}, ...]
我找到了完整的解决方案。
mongo_db['users'].find().to_a.each do |u|
u['id'] = u.delete '_id'
end.to_json
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"}]
如果您不想修改原始数组,请执行以下操作:
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"}]