Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moped: get id after inserting

When I use mongo-ruby-driver and I insert new document it returns generated '_id':

db = MongoClient.new('127.0.0.1', '27017').db('ruby-mongo-examples')
id = db['test'].insert({name: 'example'})

# BSON::ObjectId('54f88b01ab8bae12b2000001')

I'm trying to get the '_id' of a document after doing an insertion using Moped:

db = Moped::Session.new(['127.0.0.1:27017'])
db.use('ruby-mongo-examples')
id = db['coll'].insert({name: 'example'})

# {"connectionId"=>15, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}

How I get the id using Moped?

Update:

I also try use safe mode but it doesn't work:

db = Moped::Session.new(['127.0.0.1:27017'])
db.use('ruby-mongo-examples')

db.with(safe: true) do |safe|
  id = safe['coll'].insert({name: 'example'})

  # {"connectionId"=>5, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}
end
like image 292
drinor Avatar asked Mar 05 '15 17:03

drinor


Video Answer


1 Answers

After inserting/saving, the returned object will have a property inserted_id which is a BSON::ObjectId:

# I'm using insert_one
result = safe['coll'].insert_one({name: 'example'})   
result.methods.sort        # see list of methods/properties
result.inserted_id
result.inserted_id.to_s    # convert to string
like image 88
hamster ham Avatar answered Oct 12 '22 17:10

hamster ham