mongodbmongoidmoped

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

Solution

  • 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]