助力车:插入后获取ID

Moped: get id after inserting

当我使用 mongo-ruby-驱动程序并插入新文档时,它 returns 生成了 '_id':

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

# BSON::ObjectId('54f88b01ab8bae12b2000001')

我试图在使用 Moped 进行插入后获取文档的“_id”:

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}

如何使用 Moped 获取 ID?

更新:

我也尝试过使用安全模式,但它不起作用:

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

从这个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.

最好的办法是在插入文档之前生成 ID:

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

在inserting/saving之后,返回的对象会有一个属性 inserted_id,也就是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