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

  • 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.
主站蜘蛛池模板: 内黄县| 济阳县| 额敏县| 建湖县| 小金县| 梁平县| 横峰县| 陇川县| 绩溪县| 绥滨县| 云梦县| 乌拉特后旗| 昭平县| 石楼县| 东乡族自治县| 潞西市| 丹江口市| 华安县| 虎林市| 奎屯市| 桑植县| 中阳县| 上饶县| 嘉义市| 青州市| 绥中县| 舞钢市| 修武县| 金乡县| 荆门市| 靖边县| 青海省| 左贡县| 乐业县| 慈溪市| 庄河市| 饶平县| 宁德市| 涞水县| 崇信县| 内江市|