开发者

Ruby Mongo Driver - Find_by_Id

What am I doing wrong here? I know the _id is in the database but I get empt开发者_如何学Pythony result.

@b = coll.find("_id" => "4db2ebee90036f010b000001")

Thanks


Use this:

coll.find(:_id => BSON::ObjectId('4db2ebee90036f010b000001')).each do |data| 
   puts data.inspect 
end


@b will contain a cursor, not the result. You also need to use an object id proper.

You probably want this:

@b = coll.find_one(:_id => BSON::ObjectId('4db2ebee90036f010b000001'))


With Ruby 1.9.3 and mongoid 3.0.19

@coll = Coll.find( hash["_id"] )

or

@coll = Coll.find( "511296d2dfa18f07fa000009" )

find the record. Will only ever be one, _id is the primary key, it can never be double.


I would use something like first which returns a object since you have bigger problems if your primary id is duplicated in your database. The syntax is depending on your mongo gem version this one is for 2.1.0.

your_id = '4db2ebee90036f010b000001'
db = Client.new([ "localhost:27017" ], :database => "db")
coll = db[:testCollection]
res = coll.find(:_id => BSON::ObjectId(your_id)).first


Using, Ruby version 2.3.1p112, mongo (gem) 2.4.2 and BSON (gem) 4.2.2

The following worked for me

client = Mongo::Client.new(['127.0.0.1:3001'], :database=>'dbname')
collection = client[:users]
user = collection.find({_id:'XY3h5R7aJkh5FxFhJ'}).first
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜