开发者

Two "id" fields in one MongoDB collection with Rails 3?

开发者 https://www.devze.com 2023-04-12 03:50 出处:网络
I\'ve got a Rails 3.0.9 project using the latest version of MongoDB and Mongoid 2.2. I imported a CSV with an \"id\" field into a MongoDB collection named College, resulting in a collection like so:

I've got a Rails 3.0.9 project using the latest version of MongoDB and Mongoid 2.2.

I imported a CSV with an "id" field into a MongoDB collection named College, resulting in a collection like so:

{ "_id" : ObjectID("abc123"), "id" : ######, ... }

Observations:

  1. The show action results in a URL utilizing the ObjectID
  2. Displaying 'college.id' in index.html.erb displays the ObjectID

Questions:

  1. How do I use the original "id" field as the parameter
  2. Is 开发者_运维知识库"id" reserved by MongoDB, meaning I need to rename the "id" field in the College collection (perhaps to "code") - if so, how?

Thanks!

Update

Answer:

db.colleges.update( { "name" : { $exists : true } } , { $rename : { "id" : "code" } }, false, true )

I used "name" since that was a field I could check for the existence.


_id is a reserved and required property in MongoDB - I think mongoid is mapping id to _id since that makes sense. There might be a way to access the id property through mongoid but I think you are much better off renaming the id column to something else to avoid confusion in the future.

{ $rename : { old_field_name : new_field_name } }

will rename the field name in a document (mongo 1.7.2+).

so

db.college.update({ "_id" : { $exists : true }}, { $rename : { 'id' : 'code' } }, false, true);

should update every record in that collection and rename the id field to code.

(obviously test this before running in any important data)

0

精彩评论

暂无评论...
验证码 换一张
取 消