如何在mongoid中对所选属性进行投影?

时间:2011-10-20 10:10:01

标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid

我在用户模型中嵌入了许多标记的坐标模型。如何在没有_ids的情况下提取属性,以便在输出上只显示每个lng和lat?

结构:

{ "_id" : ObjectId( "4e9f418f1e7bf20fbc000009" ),
  "name" : "test",
  "coordinates" : [ 
    { "lng" : 16.86783310009764,
      "lat" : 52.38353842845282,
      "_id" : ObjectId( "4e9f418f1e7bf20fbc00000a" ) }, 
    { "lng" : 16.85787674023436,
      "lat" : 52.40972501601293,
      "_id" : ObjectId( "4e9f418f1e7bf20fbc00000b" ) }, 
    { "lng" : 16.92276474072264,
      "lat" : 52.40071858320756,
      "_id" : ObjectId( "4e9f418f1e7bf20fbc00000c" ) }, 
    { "lng" : 16.90182205273436,
      "lat" : 52.38270020105396,
      "_id" : ObjectId( "4e9f418f1e7bf20fbc00000d" ) }, 
    { "lng" : 16.96705337597655,
      "lat" : 52.410661698108,
      "_id" : ObjectId( "4e9f418f1e7bf20fbc00000e" ) }, 
    { "lng" : 16.89495559765624,
      "lat" : 52.42773236584494,
      "_id" : ObjectId( "4e9f418f1e7bf20fbc00000f" ) } ] }

e.g。

= debug @user.coordinates.to_json

给出:

--- ! '[{"_id":"4e9f418f1e7bf20fbc00000a","lat":52.383538428452816,"lng":16.86783310009764},{"_id":"4e9f418f1e7bf20fbc00000b","lat":52.40972501601293,"lng":16.85787674023436},{"_id":"4e9f418f1e7bf20fbc00000c","lat":52.40071858320756,"lng":16.92276474072264},{"_id":"4e9f418f1e7bf20fbc00000d","lat":52.382700201053964,"lng":16.90182205273436},{"_id":"4e9f418f1e7bf20fbc00000e","lat":52.410661698108,"lng":16.967053375976548},{"_id":"4e9f418f1e7bf20fbc00000f","lat":52.42773236584494,"lng":16.894955597656235}]'

预期:

--- ! '[{"lat":52.383538428452816,"lng":16.86783310009764},{"lat":52.40972501601293,"lng":16.85787674023436},{"lat":52.40071858320756,"lng":16.92276474072264},{"lat":52.382700201053964,"lng":16.90182205273436},{"lat":52.410661698108,"lng":16.967053375976548},{"lat":52.42773236584494,"lng":16.894955597656235}]'

2 个答案:

答案 0 :(得分:2)

尝试使用except

 @user.coordinates.to_json(:except => '_id')

答案 1 :(得分:0)

接受的答案会返回您希望的数据。我建议使用without来攻击mongoid查询,这样你实际上就不会从DB中获取数据,这是理想的。

@user.coordinates.without('_id').to_json(:except => '_id')