Creating documents

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]

Inserting a single document with our definition:

document = { isbn: '101', name: 'Mastering MongoDB', price: 30}

Can be done with a single line of code as follows:

result = @collection.insert_one(document)

The resulting object is a Mongo::Operation::Result class with content similar to what we had in the shell:

{"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:

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 now we have an attribute, inserted_ids, which will return ObjectId of the inserted objects from the BSON::ObjectId class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.212.196