MongoDB Basics (Select, Insert, Update and Delete)

MongoDB is a NoSQL, cross-plataform, document-oriented database, it was first developed in 2007 and has gained a lot of friction ever since. In this tutorial we’re going to go over all the basic CRUD operations with mongoDB, which are: Select, Insert, Update and Delete.

Before we begin make sure you have your MongoDB correctly installed and also a connection established, with your environment set let’s get started by creating our first collection and inserting some data on it.

Inserting Data

MongoDb works with JSON-like documents, so we’re going to pass the data in this format. The first thing we need to know is the collection that we’re going store the data (collections are equivalent to tables in relational databases), for this example I’m going to use the collection “users”, note that I haven’t created it yet, mongo will automatically do it for me when I insert the data on it for the first time:

1
2
3
4
5
6
> db.users.insert([
{"id": 1, "first_name": "Joshua", "last_name": "Black", "email": "jblack0@nifty.com", "country": "Philippines"}, 
{"id": 2, "first_name": "Carol", "last_name": "Hall", "email": "chall1@reddit.com", "country": "Philippines"}, 
{"id": 3, "first_name": "Phillip", "last_name": "Fisher", "email": "pfisher2@symantec.com", "country":"Portugal"}, 
{"id": 4, "first_name": "Marie", "last_name": "Mills", "email": "mmills3@hhs.gov", "country": "Greece" }
])

After executing the command you should see the following output:

1
2
3
4
5
6
7
8
9
10
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 4,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

It means that you’ve successfully inserted four rows in your collection, now that we already have some data let’s learn how to query them.

Selecting and Filtering Data

To select the documents from a collection we can use the find() method, here are some examples of its usage:

Bring all the data:

1
> db.users.find()

Filter by an attribute:

1
> db.users.find({"id":1})

AND condition:

1
> db.users.find({"country":"Philippines","first_name":"Carol"})

OR condition:

1
> db.users.find({$or:[{"country":"Greece"},{"country":"Portugal"}]})

$lt and $gt operators (< and >):

1
2
> db.users.find({"id":{$lt:2}})
> db.users.find({"id":{$gt:2}})

Updating Data

MongoDB provides the method update() to perform documents modifications, we can pass the filters as the first parameter, mongo will update only the documents that matches with them, in the example bellow I’ve passed {“id”:1} as the first argument, which means I want to update only the documents with id = 1. The second parameter is where we pass the actual modifications, I’m changing the first_name to “Phill” and the country to “Italy”.

1
2
3
4
5
6
7
8
9
db.users.update(
    {"id":1}, 
    {
        $set:{
           "first_name":"Phill",
           "country":"Italy",
       }
    }
)

This will be the output:

1
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Removing Data

Lastly we’re going to remove the documents with the method remove(), its usage is quite like the find() method, we can use it with no arguments to remove all the documents or we can specify a condition:

Remove all the data:

1
> db.users.remove()

Remove with a condition:

1
> db.users.remove({"id":1})

For more information see the MongoDB Manual.

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>