mahemoff
mahemoff

Reputation: 46509

Ruby Mongo - Get back ID after insert

For example:

result = collection.insert_one({ name: 'test' })

Now how do I get back the ID of the new document, assuming it was successfully inserted? Is there any way to get it from result? Seems to be possible with some languages/drivers but can't see how to do it with default Ruby Mongo driver, unless I ran a query afterwards.

Upvotes: 0

Views: 1009

Answers (2)

Hamza BEN KHALDOUN
Hamza BEN KHALDOUN

Reputation: 31

You can also do this

oid = result.inserted_id

plz refer to official docs

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

You can first generate the id and then send the insert with the id included.

oid = BSON::ObjectId.new
result = collection.insert_one({ _id: oid, name: 'test'})

This way you have all the info already and don't need to get anything back.

Upvotes: 3

Related Questions