- Mastering MongoDB 3.x
- Alex Giamas
- 325字
- 2021-08-20 10:10:54
Scripting for the mongo shell
Administering the database using built-in commands is helpful but is 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:
> 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.
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, the isbn value. With the data that we have in our collection we can use our new function and get back books by ISBN:
> 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 .js files and invoke them directly from the command line:
$ mongo <script_name>.js
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. Write concern 1 will request an ack that the write operation has propagated to the standalone mongod or the primary 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.