Basic CRUD with MongoDB

This article will cover:

MongoDB Connecting

To start using MongoDB go to your cmd or shell and type "mongo" after completing the installation of MongoDB. after that type "db" to see the current database (by default it is "test").

yamicode> mongo
#some information about your server

> db
test

Database Manipulation

In order to create or use a database we use the "use databaseName". In this tuto i'll use a database named "yamicode". But before that we'll list our databases to see that MongoDB already came with 3 databases already created (admin, local, test).

List databases

> show dbs

Create database

> use yamicode
switched to db yamicode

See the current used database

> db
yamicode

If you use the command "show dbs" it will not return yamicode bacause a database in MongoDB are created if you insert a document inside of it.

Drop and delete a database

>use yamicode
switched to db yamicode

> db.dropDatabase()
{ "dropped" : "yamicode", "ok" : 1 }

Collections

A collection are like a database in MongoDB you only see it after you insert some document inside of it. In order to see some result we'll add some document just for testing purpose

Creating a collection

In this case the collection name is "test". to use a collection we use the db."collectioname".method to use. We'll know more about those methods in a while.

> db.test.insert({name: "something"})
WriteResult({ "nInserted" : 1 })

Every document in MongoDB has an "_id" field if not specified in the json object, MongoDB will generate one for you. The object created before is: { "_id" : ObjectId("5e2f3e9a639f39df1eb90eee"), "name" : "something" }

List collections

> show collections
test

Drop collections

> db.test.drop()
true

Inserting and creating Documents

Inserting document in MongoDB are so easy because it has no schema and the documents doens't has to have the same schema so you can imagine any kind of json object and make it a document inside of a MongoDB collection. we'll use the "test" collection but feel free to use any name you want (See more about insert: [Insert and create documents in MongoDB]).

Inserting a single document

To insert a document we use the "insert" method

> db.test.insert({
  name: "something",
  types: [
    "type1",
    "type2"
  ],
  nbr: 52,
  created_date: new
  Date(
  "2017-10-10"
  ),
  metadata: {
    meta1: "value1",
    meta2: "value2"
  }
})

Inserting multiple documents

To insert multiple documents we use the "insert method" but this time we send as a parameter a list of json objects instead of one.

> db.test.insert([
{
  name: "something",
  types: [
    "type1",
    "type2"
  ],
  nbr: 52,
  created_date: new
  Date(
  "2017-10-10"
  ),
  metadata: {
    meta1: "value1",
    meta2: "value2"
  }
},
{
  name: "something2",
  types: [
    "type1",
    "type2"
  ],
  nbr: 20,
  other_field: "field not on the other object",
  created_date: new
  Date(
  "2017-10-10"
  ),
  metadata: {
    meta5: "value1",
    meta6: "value2"
  }
}
])

Select and Query collections and documents

In order to query our collections we'll use the "find" method. find method take two object:

  • Query: like a where clause in an RDBMS but as an object. If the object are not passed to the parameter or the object has no field the find method will return all the collection inside this collection (See more about query operators: [Query operators]).
  • Projection: like a select fields where you choose the fields to select. If the object are not passed to the parameter or the object has no field the find method will return all the fields

Get all documents inside a collection

> db.test.find()
> db.test.find({})
> db.test.find({},{})

SQL equivalent

SELECT * from test;

Result

{ "_id" : ObjectId("5e2f446bf098cf25b5b434c6"), "name" : "something", "types" : [ "type1", "type2" ], "nbr" : 52, "created_date" : ISODate("2017-10-10T00:00:00Z"), "metadata" : { "meta1" : "value1", "meta2" : "value2" } }
{ "_id" : ObjectId("5e2f446bf098cf25b5b434c7"), "name" : "something2", "types" : [ "type1", "type2" ], "other_field" : "field not on the other object", "created_date" : ISODate("2017-10-10T00:00:00Z"), "metadata" : { "meta5" : "value1", "meta6" : "value2" } }

Adding The Query or the Where equivalent clause in Find

In this table we'll list some of the basics where operations in MongoDB. how to write them and what is the equivalent in the SQL.

Operation MongoDB find SQL
Equality {field_name: "something"} where field_name="something"
Not equal {field_name: {$ne: "something"}} where field_name!="something"
Less than or equal {field_name: {$lte: 30}} where field_name<=30
Greater than or equal {field_name: {$gte: 30}} where field_name>=30
Less than {field_name: {$lt: 30}} where field_name<30
Greater than {field_name: {$gt: 30}} where field_name>30

Example of find with query parameter

> db.test.find({nbr: {$lte: 30}})
> db.test.find({name: "something"})
> db.test.find({_id: ObjectId("5e2f446bf098cf25b5b434c6")})

The AND operator in MongoDB

To use the "and" operator you have to add a key in the query object named "$and" that takes as values an array of operations.

Global syntax

> db.test.find({
	$and: [
		{name: "something2"},
		{nbr: {$lte: 30}}
	]
})

Minified syntax

If a query has only the and operators you can remove the $and operator as it is the default way that MongoDB handle a list of given object like the following example.

> db.test.find({
	name: "something2",
	nbr: {$lte: 30}
})

The OR operator in MongoDB

To use the "or" operator you have to add a key in the query object named "$or" that takes as values an array of operations.

> db.test.find({
	$or: [
		{name: "something"},
		{nbr: {$lte: 30}}
	]
})

The Pretty method in MongoDB

In order to see a better visualisation and presentation of object you can add the "pretty" method to the find.

> db.test.find({
	$or: [
		{name: "something"},
		{nbr: {$lte: 30}}
	]
}).pretty()

Result of pretty

{
        "_id" : ObjectId("5e2f4a6cf098cf25b5b434ca"),
        "name" : "something",
        "types" : [
                "type1",
                "type2"
        ],
        "nbr" : 52,
        "created_date" : ISODate("2017-10-10T00:00:00Z"),
        "metadata" : {
                "meta1" : "value1",
                "meta2" : "value2"
        }
}
{
        "_id" : ObjectId("5e2f4a6cf098cf25b5b434cb"),
        "name" : "something2",
        "types" : [
                "type1",
                "type2"
        ],
        "nbr" : 20,
        "other_field" : "field not on the other object",
        "created_date" : ISODate("2017-10-10T00:00:00Z"),
        "metadata" : {
                "meta5" : "value1",
                "meta6" : "value2"
        }
}

Projection in MongoDB

Projection in mongoDB means to select the nessacery fields instead of all the fields (See more about projection: [Projection in MongoDB]).

RDBMS example of projection

In RDBMS to use projection we define the column that we need instead of "*".

select id, name from yamicode;

Projection in MongoDB

The projection method takes as parameter a JSON object that takes as key the name of the field and as a value either 0 (hide) or 1 (show)

Inclusion: Getting the field name and types from MongoDB projection
> db.test.find({}, {name: 1, types: 1})
exclusion: Removing the field name and types from MongoDB projection
> db.test.find({}, {name: 0, types: 0})
Removing _id from inclusion in MongoDB projection
> db.test.find({}, {name: 1, types: 1, _id: 0})

Except for the _id you can't mix inclusion (1) and exclusion (0) in the same query. You have only two choices either you planning on hiding or showing fields it depends on your case. The _id field can take a 0 in an inclusion projection because it's added by default to the inclusion projection

Update documents

In order to update a document we use the method "update", "updateOne" or "updateMany" (See more about update: [Update documents in MongoDB]). The update method takes 3 parameters

Update parameters

  • Query: which objects you want to update and it has the same syntax as find
  • Update: fields to update
  • Object: additional data that concern the update like
    • upsert (boolean): insert the element if not found
    • multi (boolean): update multiple document at once

Update examples

Update all the document with the new values except the id

> db.test.update({name: "something"}, {name: "edited", "field2": "value"})

Update only the nessacery fields and save the other fields

> db.test.update({name: "edited"}, {$set: {name: "somthing2"}})

Update all document

> db.test.updateMany({}, {$set: {name: "somthing2"}})
  • The main difference between update and (updateMany and updateOne) is that with the last two you can't update all the document at once or you'll get the error: uncaught exception: Error: the update operation document must contain atomic operators
  • The difference between update with default options (multi equal false) and updateMany is that update only modify the first document found

Delete documents

To delete a document we use the method "remove", "deleteOne" or "deleteMany" (See more about delete: [Remove and delete documents in MongoDB]). Remove method takes two parameters

Delete parameters

  • Query: which objects you want to delete and it has the same syntax as find
  • Object: additional data that concern the remove
    • justOne (boolean): remove only one element (default value false)

Delete examples

Delete all documents

> db.test.remove({})

Remove using query

> db.test.remove( { nbr: { $gt: 20 } } )