Working with the Mongo shell

Whenever we start using MongoDB, the first thing we should do is play with it for a while. Looking for available databases, collections, documents, and so on can be done with a simple tool called Mongo shell. This shell is packaged along with the installation steps we mentioned in the preceding section. We need to launch it using the following command:

mongo

Refer to the following screenshot:

 

If you see this screen, everything worked fine. If you are getting any errors, the server is not running or there is some other issue. For troubleshooting, you can look at the official MongoDB troubleshooting guide at https://docs.mongodb.com/manual/faq/diagnostics. The client gives the information about MongoDB versions and other warnings. To see all available shell commands, use the help command.

Now we are ready with our setup. Let us create a new collection called movies and insert the preceding example document into it. By default, the database will be a test database. You can switch to a new database using the use command:

> show databases

It shows all available databases. By default, admin, test, and local are the three databases available. In order to create a new database, just use use db_name:

> use appdb

This switches the current database to the appdb database. If you try to see this in the available databases, it won't show up because MongoDB creates a database only when data is inserted into it (first collection or document). So, now we can create a new collection by inserting a document from the shell. Then, we can insert the preceding Star Trek movie record into a collection called movies, using this command:

> db.movies.insertOne({ _id: 5, name: 'Star Trek', year: 2009, directors: ['J.J. Abrams'], writers: ['Roberto Orci', 'Alex Kurtzman'], boxOffice: { budget:150000000, gross:257704099 } } )
{
"acknowledged" : true,
"insertedId" : 5
}

The JSON you inserted has an ID called _id. We can either provide it while inserting a document or MongoDB can insert one for you itself. In SQL databases, we use auto-increment along with an ID schema to increment the ID field. Here, MongoDB generates a unique hash ID rather than a sequence. Let us insert one more document about The Dark Knight, but this time let us not pass the _id field:

> db.movies.insertOne({ name: 'The Dark Knight ', year: 2008, directors: ['Christopher Nolan'], writers: ['Jonathan Nolan', 'Christopher Nolan'], boxOffice: { budget:185000000, gross:533316061 } } )> db.movies.insertOne({ name: 'The Dark Knight ', year: 2008, directors: ['Christopher Nolan'], writers: ['Jonathan Nolan', 'Christopher Nolan'], boxOffice: { budget:185000000, gross:533316061 } } )
{
"acknowledged" : true,
"insertedId" : ObjectId("59574125bf7a73d140d5ba4a")
}

If you observe the acknowledgement JSON response, insertId has now changed to a very lengthy 59574125bf7a73d140d5ba4a. This is the unique hash generated by MongoDB. Now, let us see all the documents in our collection. We can also insert a batch of documents at a given time using an insertMany function:

> db.movies.find()

{ "_id" : 5, "name" : "Star Trek", "year" : 2009, "directors" : [ "J.J. Abrams" ], "writers" : [ "Roberto Orci", "Alex Kurtzman" ], "boxOffice" : { "budget" : 150000000, "gross" : 257704099 } }
{ "_id" : ObjectId("59574125bf7a73d140d5ba4a"), "name" : "The Dark Knight ", "year" : 2008, "directors" : [ "Christopher Nolan" ], "writers" : [ "Jonathan Nolan", "Christopher Nolan" ], "boxOffice" : { "budget" : 185000000, "gross" : 533316061 } }

Using the find function on the movies collection returns all matched documents in the collection. In order to return a single; document, use the findOne function. It returns the latest document from multiple results:

> db.movies.findOne()

{ "_id" : 5, "name" : "Star Trek", "year" : 2009, "directors" : [ "J.J. Abrams" ], "writers" : [ "Roberto Orci", "Alex Kurtzman" ], "boxOffice" : { "budget" : 150000000, "gross" : 257704099 }}

How do we fetch a document with some criteria? This means querying. Querying in MongoDB is known as filtering data and returning a result. If we need to filter for movies that were released in 2008, then we can do this:

> db.movies.find({year: {$eq: 2008}})

{ "_id" : ObjectId("59574125bf7a73d140d5ba4a"), "name" : "The Dark Knight ", "year" : 2008, "directors" : [ "Christopher Nolan" ], "writers" : [ "Jonathan Nolan", "Christopher Nolan" ], "boxOffice" : { "budget" : 185000000, "gross" : 533316061 } }

The filter query from the preceding mongo statement is:

{year: {$eq: 2008}}

This states that the searching criteria is the year and the value should be 2008. $eq is called a filtering operator, which helps to relate the condition between the field and data. It is equivalent to the = operator in SQL. In SQL, the equivalent query can be written as:

SELECT * FROM movies WHERE year=2008;

We can simplify the last written mongo query statement to this:

> db.movies.find({year: 2008})

This find query and above mongo query were the same, returning the same set of documents. The former syntax is using the $eq which is a query operator. From now on, let us call a query operator simply an operator. Other operators are:

Operator Function
$lt Less than
$gt Greater than
$in In the
$lte Less than or equal to
$ne Not equal to

 

Now, let us pose a question to ourselves. We want to fetch all the documents whose budget is more than $150,000,000. How can we filter it with the knowledge we gained previously? Take a look at the following code snippet:

> db.movies.find({'boxOffice.budget': {$gt: 150000000}})

{ "_id" : ObjectId("59574125bf7a73d140d5ba4a"), "name" : "The Dark Knight ", "year" : 2008, "directors" : [ "Christopher Nolan" ], "writers" : [ "Jonathan Nolan", "Christopher Nolan" ], "boxOffice" : { "budget" : 185000000, "gross" : 533316061 } }

If you observe, we accessed the budget key within the JSON using boxOffice.budget. The beauty of MongoDB is that it allows us to query the JSON with a lot of freedom. Can't we add two or more operators to the criteria while fetching documents? Yes, we can! Let us find all movies in the database that were released in 2009 with a budget of more than $150,000,000:

> db.movies.find({'boxOffice.budget': {$gt: 150000000}, year: 2009})

This returns nothing because we don't have any documents that match the given criteria. Comma-separated fields actually combine with the AND operation. Now, let us relax our condition and find movies that were either released in 2009 or had a budget of more than $150,000,000: 

> db.movies.find({$or: [{'boxOffice.budget': {$gt: 150000000}}, {year: 2009}]})

{ "_id" : 5, "name" : "Star Trek", "year" : 2009, "directors" : [ "J.J. Abrams" ], "writers" : [ "Roberto Orci", "Alex Kurtzman" ], "boxOffice" : { "budget" : 150000000, "gross" : 257704099 } }
{ "_id" : ObjectId("59574125bf7a73d140d5ba4a"), "name" : "The Dark Knight ", "year" : 2008, "directors" : [ "Christopher Nolan" ], "writers" : [ "Jonathan Nolan", "Christopher Nolan" ], "boxOffice" : { "budget" : 185000000, "gross" : 533316061 } }

Here, the query is bit different. We used an operator called $or for finding the predicate of two conditions. The result will be the criteria for fetching the documents. $or needs to be assigned to a list that has a list of JSON condition objects. Since JSON can be nested, conditions can also be nested. This style of querying might look new to people coming from an SQL background. The MongoDB team designed it for the intuitive filtering of data. We can also write advanced queries such as inner joins, outer joins, nested queries, and so on easily in MongoDB with the clever use of operators.

Unknowingly, we have finished three operations in CRUD. We saw how to create a database and a collection. Then, we inserted documents and read them using filters. Now it is time for the delete operation. We can delete a document from a given collection using the deleteOne and deleteMany functions:

> db.movies.deleteOne({"_id": ObjectId("59574125bf7a73d140d5ba4a")})
{ "acknowledged" : true, "deletedCount" : 1 }

The argument passed to the deleteOne function is the filtering criteria, which is similar to the read operation. All the documents that match the given criteria will be removed from the collection. The response has a nice acknowledgment message with a count of documents that got deleted.

All the preceding sections discuss the basics of MongoDB, but with the shell, which executes JavaScript statements. It is not quite useful executing db statements from the shell manually. We need to call the API of Mongo DB in Go using a driver program. In the upcoming section, we will see such a driver package called mgo. The official MongoDB drivers include languages such as Python, Java, and Ruby. Go's mgo driver is a third-party package.

..................Content has been hidden....................

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