Email Subscription Form

Sunday, July 14, 2019

The Easiest MongoDB Tutorial on the Web

MongoDB is one of the most popular non-relational databases in use today.  Its versatility, speed, and scalability make it popular with applications that need to store data in a JSON-like format.  It's very easy to install MongoDB and create a database, but the query language it uses is quite different from the SQL query language.  When I first started using MongoDB, I was frustrated by the documentation I found on queries; either they tried to explain too much or the examples were too complicated.  More than once I said things in frustration like "How can I simply ask for 'select lastName from contacts where id = 3?!!'".

It is because of this frustration that I have created this tutorial.  In the tutorial, I'll be including several really simple examples of queries that you are probably used to running in SQL. 


Installing Mongo:
Because this post is really about writing queries, I'm going to skip the installation instructions, and instead send you here for MacOSX and here for Windows.  Once you have finished the installation instructions, you should have a command window open that is running mongo.

Creating a Database:
Creating a new database is unbelievably easy.  We're going to name our new database tutorial.  To create it, simply type use tutorial.  You'll get the response switched to db tutorial.  Tada!  Your database is created.

Adding a Document:
Of course, right now your database is completely empty.  Let's change that by typing
db.tutorial.insertOne( { _id: 1, firstName: "Prunella", lastName: "Prunewhip" } ).  
You will get a response of 
{ "acknowledged" : true, "insertedId" : 1 }
You have just added your first document!  Note that a "document" is the equivalent of a "record" in a SQL database.  Your document has an id (which is preceded by an underscore, by convention), a first name, and a last name.

Retrieving All Documents:
Let's make sure that your document was really added by asking for it.  Type 
db.tutorial.find() 
and you should get this as a result: 
{ "_id" : 1, "firstName" : "Prunella", "lastName" : "Prunewhip" }
The empty find() command will find all of the documents in the database.  At the moment, we only have one document, so that's all that was returned.

Adding Multiple Documents:
To add several documents at the same time, use the InsertMany command, like this:

db.tutorial.insertMany([ { _id: 2, firstName: "Joe", lastName: "Schmoe" }, { _id: 3, firstName: "Amy", lastName: "Smith" }, { _id: 4, firstName: "John", lastName: "Smith" }, { _id: 5, firstName: "Joe", lastName: "Bagadonuts" }, { _id: 6, firstName: "Carol", lastName: "Jones" }, { _id: 7, firstName: "Robert", lastName: "Johnson" } ])

Note that each document is wrapped in curly braces, separated by commas.  You'll get a response like this: 
{ "acknowledged" : true, "insertedIds" : [ 2, 3, 4, 5, 6, 7 ] }
Now you have seven records in your database.

If you retrieve all documents at this point using db.tutorial.find(), you'll get a result like this:
{ "_id" : 1, "firstName" : "Prunella", "lastName" : "Prunewhip" }
{ "_id" : 2, "firstName" : "Joe", "lastName" : "Schmoe" }
{ "_id" : 3, "firstName" : "Amy", "lastName" : "Smith" }
{ "_id" : 4, "firstName" : "John", "lastName" : "Smith" }
{ "_id" : 5, "firstName" : "Joe", "lastName" : "Bagadonuts" }
{ "_id" : 6, "firstName" : "Carol", "lastName" : "Jones" }
{ "_id" : 7, "firstName" : "Robert", "lastName" : "Johnson" }

Retrieving a Single Document:
To retrieve a single document, use this syntax:
db.tutorial.find( { _id: 1 } ).  
This will return the document with the id of 1: 
{ "_id" : 1, "firstName" : "Prunella", "lastName" : "Prunewhip" }

Search for All Documents With a Single Value:
The previous search on id will always return just one document, because the id is unique.  If you want to search for all documents that have a particular value, you can use 
db.tutorial.find({ lastName: "Smith"}).  
This will return all documents that have the last name Smith:
{ "_id" : 3, "firstName" : "Amy", "lastName" : "Smith" }
{ "_id" : 4, "firstName" : "John", "lastName" : "Smith" }

Search for One Value in One Document:
Let's say you want to find the last name of the document with the id of 3.  To do this, type:
db.tutorial.find({ _id: 3}, {lastName:1, _id:0}).  
You will get this result:  
{ "lastName" : "Smith" }
The _id:0 is there to specify that you don't want the id returned in the response; returning the id in the response is a default behavior in MongoDB.

Return All the Values for a Specific Field:
If you wanted to get a list of all the last names in your database, you would use
db.tutorial.find({}, {lastName:1, _id:0}).  
This would return
{ "lastName" : "Prunewhip" }
{ "lastName" : "Schmoe" }
{ "lastName" : "Smith" }
{ "lastName" : "Smith" }
{ "lastName" : "Bagadonuts" }
{ "lastName" : "Jones" }
{ "lastName" : "Johnson" }

Search with "Starts With":
MongoDB uses regex to search on field values.  To search for all the documents that have last names that begin with S, you'd do this search:
db.tutorial.find({ lastName: /^S/}).  
This will return 
{ "_id" : 2, "firstName" : "Joe", "lastName" : "Schmoe" }
{ "_id" : 3, "firstName" : "Amy", "lastName" : "Smith" }
{ "_id" : 4, "firstName" : "John", "lastName" : "Smith" }

Search with "And":
If you wanted to search for a document that had a specific first name AND a specific last name, you'd search like this:
db.tutorial.find( {$and: [{ lastName: "Smith" },{ firstName: "Amy"}]} )
which would return 
{ "_id" : 3, "firstName" : "Amy", "lastName" : "Smith" }.

Search with "In":
To search for all the documents that have either the last name Smith or the last name Jones, you'd use:
db.tutorial.find({lastName :{$in :["Smith","Jones"]}}).  
This will return
{ "_id" : 3, "firstName" : "Amy", "lastName" : "Smith" }
{ "_id" : 4, "firstName" : "John", "lastName" : "Smith" }
{ "_id" : 6, "firstName" : "Carol", "lastName" : "Jones" }

Update a Document:
If you'd like to change an existing document, you can use the Update command.  For example, to change the last name of the third document from Smith to Jones, you would type:
db.tutorial.updateOne({_id: 3 }, {$set: {lastName: "Jones"}}).  
You'll get this response: 
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }.

To verify that the record was updated correctly, you can use db.tutorial.find( { _id: 3 } ), which will return { "_id" : 3, "firstName" : "Amy", "lastName" : "Jones" }.

Delete a Document:
Finally, there may be times where you want to delete a document.  This can be done with
db.tutorial.deleteOne({_id: 4 })
which will return a response of 
{ "acknowledged" : true, "deletedCount" : 1 }.

To verify that the document has been deleted, you can run db.tutorial.find() and get this response:
{ "_id" : 1, "firstName" : "Prunella", "lastName" : "Prunewhip" }
{ "_id" : 2, "firstName" : "Joe", "lastName" : "Schmoe" }
{ "_id" : 3, "firstName" : "Amy", "lastName" : "Jones" }
{ "_id" : 5, "firstName" : "Joe", "lastName" : "Bagadonuts" }
{ "_id" : 6, "firstName" : "Carol", "lastName" : "Jones" }
{ "_id" : 7, "firstName" : "Robert", "lastName" : "Johnson" }
and you can see that the document with the id of 4 is no longer in the database.

This is by no means a complete record of everything that you can do with MongoDB, but it should be enough to get you started.  You can also refer to last week's post to get a few examples of interacting with nested values in MongoDB.  I hope that you will find today's post helpful in understanding how Mongo works, and that you will use it as a reference whenever you need it.  Happy querying!

7 comments:

  1. MongoDB is one of the maximum popular non-relational databases in use these days. Its versatility, velocity, and scalability make it popular with packages that want to keep facts in a JSON-like format. It's very easy to put in MongoDB and create a database, but the query language it uses is pretty different from the SQL query language. When I first started out the use of MongoDB,I don't know about this. After reading this blog post. This post is very well Remote Working Tools. He had covered everything about Remote Working Tools To Manage Your Teams From Anywhere. you can read this post here https://storyxpress.co/blog/remote-working-tools/ here you will clear your confusion

    ReplyDelete
  2. It's very smooth to put in MongoDB and create a database, however the question language it makes use of is pretty specific from the SQL question language. When I first began the usage of MongoDB, I became annoyed by using the documentation I observed on queries; either they attempted to provide an explanation for an excessive amount of or the examples had been too complicated. Greetings, friends! I'm seeking a site where I can read SAP Consultant. May you recommend a blog. where I can read about it SAP is one such solution. According to SAP, this system money owed for seventy seven% of world transaction income. As a result, it isn't always surprising that the profession of SAP representative is in such excessive call for. One of my friends suggested this https://techbullion.com/top-5-skills-every-sap-consultant-should-have/ Please share your thoughts on this blog so that I can make an informed decision.

    ReplyDelete
  3. Creating a new database is unbelievably clean. We're going to call our new database educational. To create it, in reality type use academic. You'll get the response switched to db academic. Tada! Your database is created. I have a company. So its Understanding the significance of the topic’s sensitivity, several outsourcing companies and corporations come organized to sign confidentiality agreements and clauses and even have protection certificates to prove their adherence. For instance, if a organization is running with exceptionally touchy healthcare records, So i have followed a https://www.analyticsinsight.net/data-annotation-outsourcing-v-s-in-house-roi-and-benefits/ site for more information. Because from here, Good and expereince expert avalibale. the best information vendors are extremely vigilant and would have HIPAA compliance amongst other regulations underneath their belt. So, if statistics security is something that has been making you hesitant about outsourcing a complicated task, you need not worry about it. play a avital role in this. So You should check this site

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. "Kudos for the insightful content, I'm impressed with the quality of your posts."
    Testing tools training institute in Hyderabad

    ReplyDelete

New Blog Location!

I've moved!  I've really enjoyed using Blogger for my blog, but it didn't integrate with my website in the way I wanted.  So I&#...