6

当我使用 mongo-ruby-driver 并插入新文档时,它会返回生成的“_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
4

2 回答 2

15

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
于 2016-01-24T14:05:52.270 回答
0

从这个问题

这会很好,但不幸的是,Mongo 在插入时不会给我们任何东西(因为它会触发并忘记),并且在安全模式下,如果它在服务器上生成它,它仍然不会给我们返回 id。所以我们真的没有办法做到这一点,除非它是 MongoDB 的核心特性。

您最好的选择是在插入文档之前生成 id:

document = { _id: Moped::BSON::ObjectId.new, name: "example" } 
id = document[:_id]
于 2015-03-06T11:53:04.453 回答