官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 呼和浩特市| 南宫市| 澳门| 湾仔区| 广河县| 塔河县| 信丰县| 老河口市| 鄢陵县| 阿拉善右旗| 云浮市| 桐梓县| 定结县| 乌什县| 扬州市| 南涧| 宜君县| 南川市| 增城市| 铁力市| 同仁县| 衡阳市| 贵溪市| 杨浦区| 平和县| 澳门| 奈曼旗| 全南县| 洛阳市| 沙河市| 莒南县| 都匀市| 洪洞县| 鄂州市| 凤翔县| 盐边县| 固阳县| 象山县| 武冈市| 天等县| 比如县|