Scripting for the mongo shell

Administering the database using built-in commands is helpful, but it's not the main reason for using the shell. The true power of the mongo shell comes from the fact that it is a JavaScript shell.

We can declare and assign variables in the shell as follows:

> var title = 'MongoDB in a nutshell'
> title
MongoDB in a nutshell
> db.books.insert({title: title, isbn: 102})
WriteResult({ "nInserted" : 1 })
> db.books.find()
{ "_id" : ObjectId("59203874141daf984112d080"), "title" : "MongoDB in a nutshell", "isbn" : 102 }

In the previous example, we declared a new title variable as MongoDB in a nutshell and used the variable to insert a new document into our books collection, as shown in the following code.

As it's a JavaScript shell, we can use it for functions and scripts that generate complex results from our database:

> queryBooksByIsbn = function(isbn) { return db.books.find({isbn: isbn})}

With this one-liner, we are creating a new function named queryBooksByIsbn that takes a single argument, which is the isbn value. With the data that we have in our collection, we can use our new function and fetch books by isbn, as shown in the following code:

> queryBooksByIsbn("101")
{ "_id" : ObjectId("592035f6141daf984112d07f"), "title" : "mastering mongoDB", "isbn" : "101", "price" : 30 }

Using the shell, we can write and test these scripts. Once we are satisfied, we can store them in the .js file and invoke them directly from the command line:

$ mongo <script_name>.js

Here are some useful notes about the default behavior of these scripts:

  • Write operations will use a default write concern of 1, which is global for MongoDB as of the current version. As write concern of 1 will request an acknowledgement that the write operation has propagated to the standalone mongod server or the primary server in a replica set.
  • To get results from operations from a script back to standard output, we must use either JavaScript's built-in print() function or the mongo-specific printjson() function, which prints out results formatted in JSON.
..................Content has been hidden....................

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