我有一个模型用户,我大量使用动态属性。 当我显示用户节目时,我跳过第一组属性以跳过id等。 问题是属性按字母顺序排序,而不是按创建顺序排序 所以,例如,如果我创建用户:
MONGODB startuplab_co_development['users'].insert([{"provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_", "_id"=>BSON::ObjectId('4dc5ad606acb26049e000002'), "email"=>"dan@gmail.com", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio"}])
即使插入第二个属性是uid,当我检索键时,它们按字母顺序排序。
%h1 User
%ul
-keys = @user.attributes.keys[3..-1]
- keys.each do |key|
%li
%span
%strong= "#{key.capitalize()}:"
%span= "#{@user[key]}"
因此,例如,这将打印UID作为最后一个属性,因为它们已经排序。
First_name: Daniel
Last_name: Palacio
Name: Daniel Palacio
Provider: google
Uid: https://www.google.com/accounts/o8/id?id=AItOawl_oas_8jcY1VSTQchsc
无论如何,我可以确保属性位置保持插入顺序吗?
以下是属性排序的事件链
ruby-1.9.2-p0 > user = User.first
=> _id: 4dc5c5946acb26049e000005, _type: nil, _id: BSON::ObjectId('4dc5c5946acb26049e000005'), provider: "google", uid: "https://www.google.com/accounts/o8/id?id=AItOawl_oas_", admin: nil, email: "danpal@gmail.com", first_name: "Daniel", last_name: "Palacio", name: "Daniel Palacio">
ruby-1.9.2-p0 > user.attributes
=> {"_id"=>BSON::ObjectId('4dc5c5946acb26049e000005'), "provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_", "email"=>"danpal@gmail.com", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio"}
ruby-1.9.2-p0 > user.update_attributes(:admin => true)
=> true
ruby-1.9.2-p0 > user.attributes
=> {"_id"=>BSON::ObjectId('4dc5c5946acb26049e000005'), "provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_", "email"=>"danpal@gmail.com", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio", "admin"=>true}
ruby-1.9.2-p0 > user.save
=> true
ruby-1.9.2-p0 > user.attributes
=> {"_id"=>BSON::ObjectId('4dc5c5946acb26049e000005'), "provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_", "email"=>"danpal@gmail.com", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio", "admin"=>true}
ruby-1.9.2-p0 > user = User.first
=> #
ruby-1.9.2-p0 > user.attributes
=> {"_id"=>BSON::ObjectId('4dc5c5946acb26049e000005'), "admin"=>true, "email"=>"danpal@gmail.com", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio", "provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_"}
答案 0 :(得分:4)
好的,答案是:
基本上在更新期间,如果文档分配空间不足(例如,因为更新添加了新字段或增加现有字段),将移动文档并重新排序字段(字母数字)。
来自MOngoDB文档: http://www.mongodb.org/display/DOCS/Updating
字段(重新)订单
在更新期间,字段顺序可以 改变了。无法保证 字段顺序将是一致的,或 同样,更新后。在 如果可以应用更新 到位,然后订单将是 相同(添加适用于 结束),但如果需要移动 文件(如果是当前的 分配的空间不足以满足 更新)然后字段将是 重新排序(字母数字)。