mongodb:将对象ID转换为BSON :: ObjectId [英] mongodb: converting object ID's to BSON::ObjectId

查看:360
本文介绍了mongodb:将对象ID转换为BSON :: ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们最近将应用程序升级到了Rails3,现在我们正在使用Mongoid,并且在_id上从mongo-db检索以前的文档时遇到了问题.

We have recently upgraded our application to Rails3 and we are now using Mongoid, and we have a problem retrieving previous documents from mongo-db by _id.

在仔细调查后,旧记录(我无法通过_id检索)看起来如下:

Upon closer investigation, an old record (which I can't retrieve by _id) look as follows:

#<Audit::Log _id: 4d892bfe6bcaff4ffd000001, 
    failed: nil, request_id: "68ccb38e9e345bb7fc55331389a902a1", 
    session_id: "54940ff7e8c7336d813a872db7cb7bc0", 
    _id: "4d892bfe6bcaff4ffd000001", ... }>

好的记录具有以下结构:

and a good record has the following structure:

#<Audit::Log _id: 4d892bfe6bcaff4ffd000001, 
    failed: nil, request_id: "68ccb38e9e345bb7fc55331389a902a1", 
    session_id: "54940ff7e8c7336d813a872db7cb7bc0", 
    _id: BSON::ObjectId('4d892bfe6bcaff4ffd000001'), ... }>

如您所见,_id字段是不同的.对于旧记录,它似乎只是一个字符串,而对于新记录,它是BSON::ObjectID.

As you can see, the _id field is different. For the old records it seems to be just a string, and for the new records it is a BSON::ObjectID.

我似乎无法使用旧格式检索记录.尝试使用

I can't seem to be able to retrieve the records with the old format. Trying to find the records using

Audit::Log.where(:_id => BSON::ObjectId('4d892bfe6bcaff4ffd000001')).first
Audit::Log.where(:_id => '4d892bfe6bcaff4ffd000001').first

都返回nil.

但是为了好的记录,我可以做

But for the good record, I can just do

Audit::Log.where(:'_id' => '4e14152d6bcaff26bb000039').first

我正在猜测,但是也许Mongoid自动将字符串转换为ObjectId以便在_id上找到?我看到的唯一解决办法是转换 BSON::ObjectId的所有_id字段(如果尚未存在).但是我该怎么做?

I am guessing, but maybe Mongoid automatically converts the string to an ObjectId to find on _id? The only fix I see would be to convert all the _id-fields to BSON::ObjectId if they are not already. But how do I do that?

还是您有更好的方法?

推荐答案

哈,我应该进一步研究Mongoid文档.他们有一节描述如何升级.在升级到2.0.0.BETA.11 +的部分中,他们描述_id现在不再是String,并且它们指向此

Ha, I should have looked further at the Mongoid documentation. They have a section describing how to upgrade. In the section to upgrade to 2.0.0.BETA.11 + they describe that the _id's now no longer are String and they point to this gist to convert all your ids from string to ObjectId.

这篇关于mongodb:将对象ID转换为BSON :: ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆