1

如何重命名MongoDB 文档数组中的_id键?id

所以,我想做这个:

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

进入这个:

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

2 回答 2

3

我找到了完整的解决方案。

mongo_db['users'].find().to_a.each do |u|
  u['id'] = u.delete '_id'
end.to_json
于 2013-07-21T14:08:47.473 回答
3
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"}]
于 2013-07-21T14:14:50.467 回答