Asset 20

How to do CRUD operations in MongoDB

MongoDB is a cross-platform open-source NoSQL database. Compared to other SQL based databases which store data in tables and columns, MongoDB stores data in collections and documents. This provides a high level of flexibility and performance with automatic scaling.

Organization

  1. Data is stored in the form of collections, which in turn contain documents.
  2. A document is in JSON format, with data being stored in key value pairs.
  3. Documents do not require schemas and can be edited as you go.
  4. This data model allows us to represent heirarchial relationships in the data, similiar to how objects and classes are defined in front-end programming languages.

CRUD

In this article, we shall be looking at some basic CRUD operations in MongoDB. We will be using mongo, a Javascript shell interface to run queries directly on the database. We assume you have installed mongo on your local system and know how to start the mongo shell (if not, you can visit here).

Setup

show dbs - This command will list all the databases available to the user

use <db-name> - This command will switch the shell to use a particular database.

db.createCollection(<collection-name>) - This command is used to create a collection in the current database with the given name.

Create

Create operations in MongoDB deal with adding documents to a collection. If the collection you are adding a document to doesn't exist, the collection will automatically be created before adding the document.

Let's say we have a collection called cars to which we wish to insert a document. To do so, we use the db.collection.insert command. You would need to pass the document object in JSON format as an argument.

db.cars.insert({
  name: 'Mercedes',
  color: 'black'
});

Similarly, if you wish to insert multiple documents at once, use the db.collection.insertMany command. You would need to pass an array of documents as the argument.

db.cars.insertMany([
  {
    name: 'Volkswagen',
    color: 'blue'
  },
  {
    name: 'Audi',
    color: 'white'
  }
]);

Read

Read operations fetch documents from a collection and display it in the shell. The command for reading documents in MongoDB is db.collection.find(). This command takes in 2 optional parameters. The first one is the query and the second one is the projection. If we don't specifiy any parameters, then all the documents in a collection are fetched and displayed.

Let us try to fetch all documents from the car collection. We are using pretty method to print the results in an easy to read format.

db.cars.find().pretty();

Output:

{
	"_id" : ObjectId("5ed24643b5ac80aed3bc84cd"),
	"name" : "Mercedes",
	"color" : "black"
}
{
	"_id" : ObjectId("5ed2465cb5ac80aed3bc84ce"),
	"name" : "Volkswagen",
	"color" : "blue"
}
{
	"_id" : ObjectId("5ed2465cb5ac80aed3bc84cf"),
	"name" : "Audi",
	"color" : "white"
}

You must have noticed that apart from name and color, the documents also have an _id key. This is an autogenerated key by MongoDB and acts as the primary key for that document. The value of the _id key is guaranteed to be unique for a document within a collection.

What if we wish to fetch only those documents where the color is black? We then make use of the first optional parameter, called the query. The query is an object which contains key-value pairs, with or without the use of certain query operators, that filter the data received. In our case, we wish to receive only documents with their color value set to blue. Hence, the command will be:

db.cars.find({ color: 'blue' }).pretty();

Output:

{
  "_id": ObjectId("5ed2465cb5ac80aed3bc84ce"),
  "name": "Volkswagen",
  "color": "blue"
}

The second parameter in the find command is called the projection. This is another object that indicates which fields to return for a particular document. For example, let's say we want the above data, but without the _id field. We then pass in a projection object, mentioning that _id has to be ommitted.

db.cars.find({ color: 'blue' }, { _id: 0 });

Output:

{ "name": "Volkswagen", "color": "blue" }

For more information on how query and projection work, you can refer the official documentation.

db.collection.find returns all documents that match the query. If you wish to specifically fetch only one (or the first) document that matches the query, you can use db.collection.findOne.

Update

Update operation are used to update either a single document, or a set of documents. The basic command for updating documents in MongoDB is db.collection.update. This command has 2 mandatory parameters. The first parameter is a filter object which specifies the documents to update. The second parameter is the update object, which specifies what data needs to be updated in the filtered documents.

Let us try to update the color of the Volkswagen from blue to grey. The command for the same will be

db.cars.update({ name: 'Volkswagen' }, { $set: { color: 'grey' } });

Output:

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

In the filter object, we specify that we want to update only documents with the value of name as Volkswagen. In the update object, we add a $set object in which we specify that we wish to set the color value of such documents to grey. $set is one of many field update operators in MongoDB which is used to specify the particular fields that need to be updated. If the $set operator wasn't provided, then the entire document would have been replaced with data in the update object. In the above output, we can see that 1 document had been matched with the filter criteria and 1 document had been successfully updated as well. Let us see the updated document:

db.cars.find().pretty();

Output

{
	"_id" : ObjectId("5ed24643b5ac80aed3bc84cd"),
	"name" : "Mercedes",
	"color" : "black"
}
{
	"_id" : ObjectId("5ed2465cb5ac80aed3bc84ce"),
	"name": "Volkswagen",
	"color" : "grey"
}
{
	"_id" : ObjectId("5ed2465cb5ac80aed3bc84cf"),
	"name" : "Audi",
	"color" : "white"
}

Let us see now try to update the color to silver, but without the $set operator.

db.cars.update({ name: 'Volkswagen' }, { color: 'silver' });

Output:

WriteResult({ nMatched: 1, nUpserted: 0, nModified: 1 });
db.cars.find().pretty();

Output

{
	"_id" : ObjectId("5ed24643b5ac80aed3bc84cd"),
	"name" : "Mercedes",
	"color" : "black"
}
{
	"_id" : ObjectId("5ed2465cb5ac80aed3bc84ce"),
	"color" : "silver"
}
{
	"_id" : ObjectId("5ed2465cb5ac80aed3bc84cf"),
	"name" : "Audi",
	"color" : "white"
}

We see that the color was changed but the name key no longer exists. This is because, in the absence of the $set operatory, the entire document (with the exception of the _id key) was replaced with the contents of the update object. Hence, one needs to be careful to use the correct syntax while executing a MongoDB update command, in order to prevent an accidental replace instead of update.

MongoDB also provides in-built support for what is commonly called as an upsert. An upsert operation is a special type of operation wherein a document is matched and updated. If that document to be updated doesn't exist in the first place, then a new document is created and inserted with the given values. We can specify an update operation in MongoDB to be an upsert by passing in an optional argument in the form of an upsert object.

Let us see an example of how we update all documents with the name as Lamborghini to be of color yellow. The usual command would be:

db.cars.update({ name: 'Lamborghini' }, { $set: { color: 'yellow' } });

Output:

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

We see that we both filtered zero documents as well as modified zero documents. Let us try the same command but with the upsert argument.

db.cars.update(
  { name: 'Lamborghini' },
  { $set: { color: 'yellow' } },
  { upsert: true }
);

Output:

WriteResult({
  "nMatched": 0,
  "nUpserted": 1,
  "nModified": 0,
  "_id": ObjectId("5eda7a81079c90101a83d2fc")
})

We can see that although we filtered zero documents, we have 'upserted' 1 document with the document ID being returned as well. Let us try to look for the document with that ID.

db.cars.find({ _id: ObjectId('5eda7a81079c90101a83d2fc') });

Output:

{
  "_id": ObjectId("5eda7a81079c90101a83d2fc"),
  "name": "Lamborghini",
  "color": "yellow"
}

Just like in read, you can also specify that you wish to update only one (or the first) document that matches the filter object using the db.collection.updateOne command.

Delete

Delete operation are used to delete either a single document, or a set of documents. There are two commands in MongoDB for the same, db.collection.deleteOne for deleting a single document and db.collection.deleteMany() for deleting multiple documents. Both commands have 1 mandatory paramter, the filter object, which specifies the document(s) that need to be deleted.

Let us try to delete the Mercedes document. The command for the same will be:

db.cars.deleteOne({ name: 'Mercedes' });

Output:

{ "acknowledged": true, "deletedCount": 1 }

You can see that the output returns acknowledged as true, which indicates a success operation, as well as the number of documents that have been deleted, which in this case is 1.

If you would like to delete all documents in a collection, simply pass an empty filter object to the deleteMany command like this:

db.cars.deleteMany({});

AltCampus helps you learn faster by inculcating these systems as part of the learning model. ๐Ÿ™Œ

START LEARNING

Other Posts