2014-04-03 87 views
0

我有一個數據結構,看起來像:查詢的MongoDB的ObjectId使用Ruby驅動程序

{ 
    "_id" : ObjectId("533c3ce0ccf205e24fead6b8"), 
    "_class" : "test", 
    "test" : { 
     "_id" : "0502b397-4cd9-4781-bb63-70b96d799cdb", 
     "mongoTestGroups" : [ DBRef("sg", ObjectId("533c3ce0ccf205e24fead6b9")) ] 
    }, 
    "createDate" : ISODate("2014-04-02T16:37:52.175Z") 
} 

我有一個時間查詢第一的ObjectId赫克。教程/ rdoc並不完全清楚如何去做這件事。我目前有:

require 'json' 
require 'mongo' 
require 'pp' 

include Mongo 

db = MongoClient.new('localhost').db('mytest') 
coll = db.collection('testcollection') 

我相信它應該是這樣的:

pp coll.find({_id: => { ObjectId("533c3ce0ccf205e24fead6b8")}}) 

什麼工作正常是:

pp coll.count 

回答

0

您需要使用BSON::ObjectId.from_string你的ID字符串轉換爲MongoDB期待的BSON::ObjectId

coll.find(_id: BSON::ObjectId.from_string('533c3ce0ccf205e24fead6b8')) 

BSON::ObjectId.from_string調用是Ruby等價於在MongoDB shell中調用ObjectId。你很快就會發現,調用BSON::ObjectId.from_string所有的地方很麻煩,所以你可能要一個to_bson_id修補成字符串和NilClass:

class String 
    def to_bson_id 
    BSON::ObjectId.from_string(self) 
    end 
end 

class NilClass 
    def to_bson_id 
    self 
    end 
end 

然後你可以說這樣的話'533c3ce0ccf205e24fead6b9'.to_bson_idsome_string.to_bson_id代替。

如果您還在使用Mongoid,MongoMapper或其他一些ODM,那麼您也可以將to_bson_id補丁添加進去;例如,與Mongoid(使用替代MongoDB的標準接口助力車)我這樣做:

class String 
    def to_bson_id 
    Moped::BSON::ObjectId(self) # This is Moped's version of BSON::ObjectId.from_string 
    end 
end 

module Mongoid 
    module Document 
    def to_bson_id 
     id  
    end 
    end 
end 

module Moped 
    module BSON 
    class ObjectId 
     def to_bson_id 
     self  
     end 
    end 
    end 
end 

class NilClass 
    def to_bson_id 
    self 
    end 
end 

這樣我就可以說:

str.to_bson_id 
some_bson_id.to_bson_id 
some_odm_object.to_bson_id 

不關心什麼樣的事情我的工作。

相關問題