Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
MongoDB Cookbook - Second Edition

You're reading from   MongoDB Cookbook - Second Edition Modern Database Management Made Easy

Arrow left icon
Product type Paperback
Published in Jan 2016
Publisher
ISBN-13 9781785289989
Length 370 pages
Edition 2nd Edition
Tools
Arrow right icon
Authors (2):
Arrow left icon
Amol Nayak Amol Nayak
Author Profile Icon Amol Nayak
Amol Nayak
Cyrus Dasadia Cyrus Dasadia
Author Profile Icon Cyrus Dasadia
Cyrus Dasadia
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Installing and Starting the Server 2. Command-line Operations and Indexes FREE CHAPTER 3. Programming Language Drivers 4. Administration 5. Advanced Operations 6. Monitoring and Backups 7. Deploying MongoDB on the Cloud 8. Integration with Hadoop 9. Open Source and Proprietary Tools A. Concepts for Reference Index

Connecting to a single node in the Mongo shell with JavaScript

This recipe is about starting the mongo shell and connecting to a MongoDB server. Here we also demonstrate how to load JavaScript code in the shell. Though this is not always required, it is handy when we have a large block of JavaScript code with variables and functions with some business logic in them that is required to be executed from the shell frequently and we want these functions to be available in the shell always.

Getting ready

Although it is possible to run the mongo shell without connecting to the MongoDB server using mongo --nodb, we would rarely need to do so. To start a server on the localhost without much of a hassle, take a look at the first recipe, Installing single node MongoDB, and start the server.

How to do it…

  1. First, we create a simple JavaScript file and call it hello.js. Type the following body in the hello.js file:
    function sayHello(name) {
      print('Hello ' + name + ', how are you?')
    }
  2. Save this file at the location, /mongo/scripts/hello.js. (This can be saved at any other location too.)
  3. On the command prompt, execute the following:
    > mongo --shell /mongo/scripts/hello.js
    
  4. On executing this, we should see the following printed to our console:
    MongoDB shell version: 3.0.2
    connecting to: test
    >
    
  5. Test the database that the shell is connected to by typing the following command:
    > db
    

    This should print out test to the console.

  6. Now, type the following command in the shell:
    > sayHello('Fred')
    
  7. You should get the following response:
    Hello Fred, how are you?
    

Note

Note: This book was written with MongoDB version 3.0.2. There is a good chance that you may be using a later version and hence see a different version number in the mongo shell.

How it works…

The JavaScript function that we executed here is of no practical use and is just used to demonstrate how a function can be preloaded on the startup of the shell. There could be multiple functions in the .js file containing valid JavaScript code—possibly some complex business logic.

On executing the mongo command without any arguments, we connect to the MongoDB server running on localhost and listen for new connections on the default port 27017. Generally speaking, the format of the command is as follows:

mongo <options> <db address> <.js files>

In cases where there are no arguments passed to the mongo executable, it is equivalent to the passing of the db address as localhost:27017/test.

Let's look at some example values of the db address command-line option and its interpretation:

  • mydb: This will connect to the server running on localhost and listen for a connection on port 27017. The database connected will be mydb.
  • mongo.server.host/mydb: This will connect to the server running on mongo.server.host and the default port 27017. The database connected will be mydb.
  • mongo.server.host:27000/mydb: This will connect to the server running on mongo.server.host and the port 27000. The database connected will be mydb.
  • mongo.server.host:27000: This will connect to the server running on mongo.server.host and the port 27000. The database connected will be the default database test.

Now, there are quite a few options available on the mongo client too. We will see a few of them in the following table:

Option

Description

--help or -h

This shows help regarding the usage of various command-line options.

--shell

When the .js files are given as arguments, these scripts get executed and the mongo client will exit. Providing this option ensures that the shell remains running after the JavaScript files execute. All the functions and variables defined in these .js files are available in the shell on startup. As in the preceding case, the sayHello function defined in the JavaScript file is available in the shell for invocation.

--port

The specifies the port of the mongo server where the client needs to connect.

--host

This specifies the hostname of the mongo server where the client needs to connect. If the db address is provided with the hostname, port, and database, then both the --host and --port options need not be specified.

--username or -u

This is relevant when security is enabled for mongo. It is used to provide the username of the user to be logged in.

--password or -p

This option is relevant when security is enabled for mongo. It is used to provide the password of the user to be logged in.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image