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.
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!