Moped: get id after inserting

3.5k Views Asked by At

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
2

There are 2 best solutions below

4
chridam On BEST ANSWER

From this issue:

It would be nice, but unfortunately Mongo doesn't give us anything back when inserting (since it's fire and forget), and when in safe mode it still doesn't give the id back if it generated it on the server. So there really isn't any possible way for us to do this unless it was a core feature in MongoDB.

Your best bet would be to generate the id before inserting the document:

document = { _id: Moped::BSON::ObjectId.new, name: "example" } 
id = document[:_id]
1
hamster ham On

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