解决和修复MongoDB / Mongoid ID问题

时间:2012-03-17 12:55:50

标签: ruby mongodb mongoid bson

这与一年前的另一个StackOverflow问题有关。但是,有点不同。

这是Ruby / Mongoid:2.2.6。

当我使用MongoDB时,看起来我们错误地存储了MongoDb文档的ID,因为ID上的简单查找不起作用,但是当我们对其他属性运行where查询时它返回文档。

我尝试通过使用从where返回的对象并将“id”和“_id”设置为存储字符串的BSON :: ObjectId版本来“重置”id字段。这不起作用,因为该字段仍无法查询当时的记录。

在我完全擦除磁盘(丢失数月的生产数据)并重新开始之前的任何其他建议?

编辑:在循环中重新调用的文档的示例,该文档不可检索。

{"_id"=>"4f47267193546d160b0171a2", "attribute_tags"=>[{"tag"=>"website"}, {"tag"=>"twitter"}, {"tag"=>"website"}, {"tag"=>"twitter"}], "contact_info"=>{"facebook"=>[], "success"=>true, "created_at"=>2012-02-24 05:58:06 UTC, "tags"=>[], "twitter"=>[], "email"=>[], "phone"=>[], "linkedin"=>[], "google_plus"=>[], "youtube"=>[], "contact_form"=>false}, "created_at"=>2012-02-24 05:56:01 UTC, "data"=>{"twitter_followers_count"=>112, "twitter_is_translator"=>112, "twitter_protected"=>false, "twitter_url"=>"http://www.bettyunderground.com", "twitter_verified"=>false, "twitter_statuses_count"=>2040, "twitter_listed_count"=>14, "twitter_geo_enabled"=>true, "twitter_friends_count"=>124, "twitter_created_at"=>"Fri Jul 17 21:41:00 +0000 2009", "twitter_contributors_enabled"=>false, "enriched_at"=>2012-02-24 05:58:09 UTC}, "demographics"=>{}, "description"=>"The trials and tribulations of a polemicist", "directory_ids"=>[], "forums"=>[], "found_at_url"=>"http://www.bettyunderground.com", "geographics"=>{"language"=>"en", "location"=>"San Francisco, CA"}, "hashtags"=>{"tag"=>{"website"=>true, "twitter"=>true}, "reachable_via"=>{"twitter"=>true}}, "host_names"=>[], "ignore_project_ids"=>[], "keyword_scores"=>{"return policy"=>0.0}, "keywords"=>["return policy"], "last_contact_info_update"=>2012-02-24 05:58:09 UTC, "name"=>"Betty Underground", "new_profiles"=>[{"service"=>"twitter", "user_id"=>"BettyUndergrnd", "score"=>1.0}, {"service"=>"twitter", "username"=>"BettyUndergrnd", "score"=>1.0}], "presence_score"=>0, "profile_url"=>"http://a2.twimg.com/profile_images/1459407098/image_normal.jpg", "profiles_retrieved"=>true, "references"=>[], "share_counts"=>{}, "tags"=>["website", "twitter"], "twitter"=>"BettyUndergrnd", "updated_at"=>2012-03-17 10:08:09 UTC, "wordsmaster_ids"=>[], "reachable_via"=>[], "read_project_ids"=>[]}

它没有ID字段的ObjectId。不确定它是如何以这种方式被破坏的,但这就是它的方式。

我用来修改它的代码是:

#if d is the document 
old_id = d._id
d["_id"] = BSON::ObjectId(old_id)
d.save

我已经从我的控制台放置了这样做的要点。你可以看到我在做什么。

任何想法都将不胜感激。

https://gist.github.com/2087011

2 个答案:

答案 0 :(得分:2)

_id字段是不可变的。您必须插入一个新文档_id并删除旧文档。

答案 1 :(得分:0)

在Mongoid中,有一个rake任务来转换ObjectIds。

如果你使用它,你将拥有你的收藏的镜子。然后,只需重命名即可设置。

如果你有重复的object_ids会出错,所以你可能需要运行几次。

而且,它很慢。