Using the process described in Chapter 2, Schema Design and Data Modeling, we assume that we have an @collection instance variable pointing to our books collection in a mongo_book database in the 127.0.0.1:27017 default database:
@collection = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'mongo_book').database[:books]
We insert a single document with our definition, as follows:
document = { isbn: '101', name: 'Mastering MongoDB', price: 30}
This can be performed with a single line of code as follows:
result = @collection.insert_one(document)
The resulting object is a Mongo::Operation::Result class with content that is similar to what we had in the shell, as shown in the following code:
{"n"=>1, "ok"=>1.0}
Here, n is the number of affected documents; 1 means we inserted one object and ok means 1 (true).
Creating multiple documents in one step is similar to this. For two documents with isbn 102 and 103, and using insert_many instead of insert_one, we have the following code:
documents = [ { isbn: '102', name: 'MongoDB in 7 years', price: 50 },
{ isbn: '103', name: 'MongoDB for experts', price: 40 } ]
result = @collection.insert_many(documents)
The resulting object is now a Mongo::BulkWrite::Result class, meaning that the BulkWrite interface was used for improved performance.
The main difference is that we now have an attribute, inserted_ids,, which will return ObjectId of the inserted objects from the BSON::ObjectId class.