MongoDB CRUD operations in detail

In the previous post, we discussed the fundamentals of MongoDB and also introduced you to MongoDB CRUD operations. In this post we will deep dive into CRUD operations as often we use them only.

Here is the list of methods provided by MongoDB to fulfill the requirement of CRUD operations.

InsertFindUpdateDelete
insertOne()findOne()updateOne()deleteOne()
insertMany()find()UpdateMany()deleteMany()
insert()findAndModify()Update()remove()
findOneAndDelete()replaceOne()
findOneAndReplace()
findOneAndUpdate()

Let’s move further and discuss each of the methods in detail.

Create

The first operation of CRUD used to create new documents in a collection. As shown in the above table MongoDB offers three methods to create new documents. These three methods use the default write concern unless we pass a write concern and likewise the use database command it also creates a new collection if the collection is not available.

db.collection.insertOne() inserts a single document into a collection.

Syntax:

db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>
   }
)

Returns: A document containing:

  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.
  • A field inserted Id with the _id value of the inserted document.

In the below example we will insert a new document in userinfo collection. Make sure you are in the correct database. To use a database just write

use this command does two things, one creates a new database if it does not exist, and switch to the given database.

use user
switched to db user
db.userinfo.insertOne({name:'user 1',email:'user1@test.com',age:21})

#Output 
{
"acknowledged" : true,
"insertedId" : ObjectId("5ed6f5a9b66c8269070b4af2")
}

db.collection.insertMany() can insert multiple documents into a collection. This method takes an array of documents.

Syntax:

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

The ordered boolean parameter is Optional also as mentioned above it uses default concern if not provided. A boolean specifying whether the mongo instance should perform an ordered or unordered insert. Defaults to true.

Returns: A document containing:

  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled
  • An array of _id for each successfully inserted documents

Refer to the below snippet here we have created 3 documents using insert many.

db.userinfo.insertMany([

{name:'user 2',email:'user2@test.com',age:22},

{name:'user 3',email:'user3@test.com',age:32},

{name:'usr 4',email:'user4@test.com',age:30}

])

#Output 

{


"acknowledged" : true,
"insertedIds" : [
ObjectId("5ed6f6ceb66c8269070b4af3"),
ObjectId("5ed6f6ceb66c8269070b4af4"),
ObjectId("5ed6f6ceb66c8269070b4af5")
]
}

db.collection.insert() Inserts a document or documents into a collection. It works as insertOne () in case of a single document and in case of multiple documents works as insertMany ().

Syntax:

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

Returns:

  • A WriteResult object for single inserts.
  • A BulkWriteResult object for bulk inserts.

MongoDB also provide  db.collection.save() method to create documents but as per the Mongo documentation it is deprecated and they emphasize on using inserOne (), insertMany() and insert() methods.

Read

The second operation of CRUD used to read/fetch the documents from a collection. As shown in the above table MongoDB offers two methods to fetch the data from a collection.

db.collection.findOne() Returns one document that satisfies the specified query criteria on the collection or the first document from the collections if no query provided.

Syntax:

db.collection.findOne(query, projection)

Parameter

query:  The query parameter is an Optional document, which specifies a query for selection criteria using query operators.

projection: It is also an Optional document, which specifies the fields to return using projection operators. Omit this parameter to return all fields in the matching document. For details, see Projection.

Note: The basic thumb rule for applying projection is to use 1 to include any field and 0 to exclude. By default, the _id field is always included unless you explicitly exclude it.

Returns:

It returns One document that matches the criteria specified in the query, the first parameter. If you specify a projection parameter, findOne() returns a document that only contains the projection fields.

Although it is similar to the find() method, the findOne() method returns a document rather than a cursor.

Example:

db.employees.findOne({gender:'male'},{gender:1, name:1})

#Output

{
"_id" : ObjectId("5f20577536c73fc3e870fda4"),
"gender" : "male",
"name" : {
"title" : "mr",
"first" : "harvey",
"last" : "chambers"
}
}

db.collection.find() Returns document or documents that satisfies the specified query criteria on the collection.

Syntax:

db.collection.find(query, projection)

Parameter

query:  The query parameter is an Optional document, which specifies a query for selection criteria using query operators.

projection: It is also an Optional document, which specifies the fields to return using projection operators. Omit this parameter to return all fields in the matching document. For details, see Projection.

Returns:

It returns the document or documents that match the criteria specified in the query. If you specify a projection parameter, find () returns a document that only contains the projection fields.

Although it is similar to the findOne() method, the find() method returns a cursor instead of documents.

Example:

db.employees.find({},{gender:1, name:1})db.employees.findOne({gender:'male'},{gender:1, name:1})

#Output


> db.employees.find({},{gender:1, name:1})
{ "_id" : ObjectId("5f20577536c73fc3e870fda4"), "gender" : "male", "name" : { "title" : "mr", "first" : "harvey", "last" : "chambers" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda5"), "gender" : "male", "name" : { "title" : "mr", "first" : "victor", "last" : "pedersen" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda6"), "gender" : "male", "name" : { "title" : "mr", "first" : "elijah", "last" : "lewis" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda7"), "gender" : "female", "name" : { "title" : "mrs", "first" : "olav", "last" : "oehme" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda8"), "gender" : "male", "name" : { "title" : "mr", "first" : "carl", "last" : "jacobs" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fda9"), "gender" : "female", "name" : { "title" : "mrs", "first" : "madeleine", "last" : "till" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdaa"), "gender" : "female", "name" : { "title" : "miss", "first" : "shona", "last" : "kemperman" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdab"), "gender" : "female", "name" : { "title" : "ms", "first" : "louise", "last" : "graham" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdac"), "gender" : "male", "name" : { "title" : "mr", "first" : "zachary", "last" : "lo" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdad"), "gender" : "male", "name" : { "title" : "mr", "first" : "isolino", "last" : "viana" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdae"), "gender" : "female", "name" : { "title" : "mrs", "first" : "katie", "last" : "welch" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdaf"), "gender" : "female", "name" : { "title" : "miss", "first" : "sandra", "last" : "lorenzo" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb0"), "gender" : "female", "name" : { "title" : "miss", "first" : "mestan", "last" : "kaplangı" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb2"), "gender" : "male", "name" : { "title" : "mr", "first" : "gideon", "last" : "van drongelen" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb3"), "gender" : "female", "name" : { "title" : "miss", "first" : "maeva", "last" : "wilson" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb4"), "gender" : "female", "name" : { "title" : "ms", "first" : "anaëlle", "last" : "adam" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb5"), "gender" : "female", "name" : { "title" : "miss", "first" : "anne", "last" : "ruiz" } }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb6"), "gender" : "female", "name" : { "title" : "mademoiselle", "first" : "delia", "last" : "durand" } }
Type "it" for more
>

db.collection.findAndModify() Used to modifies and return a single document. By default, the returned document does not include the modifications made on the update. To return the updated document, we need to use the new option.

Syntax:

db.collection.findAndModify({
    query: <document>,
    sort: <document>,
    remove: <boolean>,
    update: <document or aggregation pipeline>,
    new: <boolean>,
    fields: <document>,
    upsert: <boolean>,
    bypassDocumentValidation: <boolean>,
    writeConcern: <document>,
    collation: <document>,
    arrayFilters: [ <filterdocument1>, ... ]
});

 

query:  The query parameter is an Optional document, which specifies a query for selection criteria using query operators similar to find() method. Although the query may match multiple documents, db.collection.findAndModify() will only select one document to modify.

sort: It is also an Optional document, determines which document the operation modifies if the query selects multiple documents. db.collection.findAndModify() modifies the first document in the sort order specified by this argument.

remove: An optional field of type boolean which must specify either to remove or update the field. Removes the document specified in the query field. Set this to true to remove the selected document. The default is false.

new: An optional boolean field. When true, returns the modified document rather than the original. The db.collection.findAndModify() method ignores the new option for remove operations. The default is false.

fields: An Optional document work similar to projection in find() method. The fields document specifies an inclusion of a field with 1, as in: fields: { : 1, : 1, … }.

For more details on parameter visit Mongo official doc

Returns:

To remove operations, if the query matches a document, it will return the removed document. If the query does not match a document to remove returns null.

For update operations, it will return one of the following:

If the new parameter is not set or is false:

  • The pre-modification document is returned if the query matches a document
  • Otherwise, null.

If new is set to true:

  • The modified document if the query returns a match
  • The inserted document if upsert: true and no document matches the query
  • Otherwise, null

Example:

db.userinfo.find({name:'test user'})

#Output

{ "_id" : ObjectId("5f444629c2254dfb46403a0a"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f4446c9c2254dfb46403a0b"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }


db.userinfo.findAndModify({
query: {name:'test user'},
update: { age: 22}
})

#Output

{
"_id" : ObjectId("5f444629c2254dfb46403a0a"),
"name" : "test user",
"email" : "testuser@test.com",
"age" : 21
}

Here you can see that it updated the document successfully but returned the old one with age 21.

If we again run the following query we will get the updated document with age 22.

db.userinfo.find({name:'test user'})

#Output

db.userinfo.find({name:'test user'})
{ "_id" : ObjectId("5f4448cbc2254dfb46403a0c"), "name" : "test user", "email" : "testuser@test.com", "age" : 22 }
{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

But, if we run the same update with one additional parameter new with the value true it will return the update document.

db.userinfo.findAndModify({
query: {name:'test user'},
update: {name:'test user',email:'testuser@test.com',age:23},
new :true
})

#Output

{
"_id" : ObjectId("5f4448cbc2254dfb46403a0c"),
"name" : "test user",
"email" : "testuser@test.com",
"age" : 23
}

db.collection.findOneAndDelete() Used to deletes a single document based on the filter and sort criteria, returning the deleted document. Deletes the first matching document in the collection that matches the filter. The sort parameter can be used to influence which document is deleted.

Syntax:

db.collection.findOneAndDelete(
   <filter>,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     collation: <document>
   }
)

Parameter

filter: The selection criteria for the deletion same as the query in find() method. Pass and empty {} document to delete the first document returned in the collection. By default, an empty document {}.

projection: Same as the projection in find() method

sort: An Optional field. Specifies a sorting order for the documents matched by the filter.

For more details on parameter visit Mongo official doc

Returns: Returns the deleted document.

Example:

db.userinfo.find({name:'test user'})
{ "_id" : ObjectId("5f4448cbc2254dfb46403a0c"), "name" : "test user", "email" : "testuser@test.com", "age" : 23 }
{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

#Output

db.userinfo.findOneAndDelete({age:23})
{
"_id" : ObjectId("5f4448cbc2254dfb46403a0c"),
"name" : "test user",
"email" : "testuser@test.com",
"age" : 23
}

Now if run the same find command again we will only get a single record with name ‘test user’

db.userinfo.find({name:'test user'})
{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

db.collection.findOneAndReplace() Used to replace a single document based on the specified filter. The sort parameter can be used to influence which document is deleted. It works the same way findAndModify() works.

Syntax:

db.collection.findOneAndReplace( 
	<filter>, <replacement>, 
	{ projection: <document>,
	 sort: <document>, 
	 maxTimeMS: <number>,
	 upsert: <boolean>, 
	 returnNewDocument: <boolean>,
	 collation: <document> 
	} 
)

Parameter

filter: The selection criteria for the deletion same as the query in find() method. Pass and empty {} document to delete the first document returned in the collection. By default, an empty document {}.

replacement: The replacement document.

projection: Same as the projection in find() method

sort: An Optional field. Specifies a sorting order for the documents matched by the filter.

returnNewDocument: An Optional field. When true, returns the replacement document instead of the original document. Defaults to false.

For more details on parameter visit Mongo official doc

Returns: Returns either the original document or the replaced document if returnNewDocument is true.

Example:

db.userinfo.find({name:'test user'})

#Output

{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbcc2254dfb46403a0e"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a0f"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a10"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

db.userinfo.findOneAndReplace(
{ "age" : 21},
{name:'test user',email:'testuserAge22@test.com',age:22}
)


#Output

{
"_id" : ObjectId("5f4448cdc2254dfb46403a0d"),
"name" : "test user",
"email" : "testuser@test.com",
"age" : 21
}

db.userinfo.find({name:'test user'})

#Output

{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuserAge22@test.com", "age" : 22 }
{ "_id" : ObjectId("5f444fbcc2254dfb46403a0e"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a0f"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a10"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

But, if we pass returnNewDocument as true, it will return the replaced document.

db.userinfo.findOneAndReplace(
{ "age" : 22},
{name:'test user',email:'testuserAge23@test.com',age:23},
{returnNewDocument : true}
)

#Output
{
"_id" : ObjectId("5f4448cdc2254dfb46403a0d"),
"name" : "test user",
"email" : "testuserAge23@test.com",
"age" : 23
}

db.collection.findOneAndUpdate() Used to update a single document based on the filter and sort criteria.

Used to replace a single document based on the specified filter. The sort parameter can be used to influence which document is deleted. It works the same way findAndModify() works.

Syntax:

db.collection.findOneAndUpdate(
   <filter>,
   <update document or aggregation pipeline>,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     upsert: <boolean>,
     returnNewDocument: <boolean>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

Parameter

filter: The selection criteria for the deletion same as the query in find() method. Pass and empty {} document to delete the first document returned in the collection. By default, an empty document {}.

update: The updated document.

projection: Same as the projection in find() method

sort: An Optional field. Specifies a sorting order for the documents matched by the filter.

returnNewDocument: An Optional field. When true, returns the replacement document instead of the original document. Defaults to false.

For more details on parameter visit Mongo official doc

Returns: Returns either the original document or the replaced document if returnNewDocument is true.

Example:
db.userinfo.find({name:'test user'})

#output

{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuserAge23@test.com", "age" : 23 }
{ "_id" : ObjectId("5f444fbcc2254dfb46403a0e"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a0f"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a10"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

db.userinfo.findOneAndUpdate(
{ "age" : 23},
{ $inc: { "age" : 2 }},
{returnNewDocument : true}
)

#output

{
"_id" : ObjectId("5f4448cdc2254dfb46403a0d"),
"name" : "test user",
"email" : "testuserAge23@test.com",
"age" : 25
}

db.userinfo.find({name:'test user'})

#output

{ "_id" : ObjectId("5f4448cdc2254dfb46403a0d"), "name" : "test user", "email" : "testuserAge23@test.com", "age" : 25 }
{ "_id" : ObjectId("5f444fbcc2254dfb46403a0e"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a0f"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }
{ "_id" : ObjectId("5f444fbec2254dfb46403a10"), "name" : "test user", "email" : "testuser@test.com", "age" : 21 }

Note: The update parameter only contains update operator expressions.  You can not pass an entire document to replace as we did in the findOneAndReplace() method.

 

Mongodb find by id, findone, find in array, find like, find limit, find count, Mongodb projection

Introduction

In the real-world application, we use a database to store the data be it a relational database or any NoSQL database. Apart from storing the data, we need to retrieve the data well. Querying the data is very important in terms of performance and memory uses. It is a good idea to fetch the relevant data only, as loading the unnecessary data will cause a performance hit as well as additional memory uses.

Mongodb

There can multiple requirements to fetch the data, in this post I will explain the following ways to fetch the data in MongoDB.

  • Mongodb find by id
  • Mongodb findone
  • Mongodb find
  • Mongodb find with limit
  • Mongodb Sort
  • Mongodb Projection
  • Mongodb find count
  • Mongodb findone latest
  • Mongodb find like
  • Mongodb find in array
  • Mongodb cursor to toArray

I have created a database company and created a collection of employees inside it and I will use the same database and collection in the entire post. You can download the sample employees’ data file from here. You can import this sample file in MongoDB using the below commands from Mongo Shell. If you are not familiar with Mongo Shell, you can check my previous post on Setting up MongoDB and an introduction to the shell.

mongoimport employees.json -d company -c employees --jsonArray

-d is the name of the database

-c is the name of the collection

If the JSON file is an array pass -–jsonArray

If you want to drop the database if it exists pass -–drop in the above command

Mongodb find

Mongodb find by id

In Mongodb, every document inside a collection will have a primary key that is denoted by _id. It is an ObjectID, one of the BSON data types of MongoDB, using this record inside a collection can be differentiated. Also, Mongodb automatically indexed this. 

As it holds a unique value for each document, we can fetch that particular document using this. Let’s check it with an example. 

Let’s fetch the employee having id ObjectId(“5f20577536c73fc3e870fda3”), run the following command to fetch it. You can use pretty() to print the output in more readable format.

Command: db.collectionName.find({_id : })

Example: db.employees.find({_id:ObjectId(“5f20577536c73fc3e870fdb6”)})

With pretty print

Command: db.collectionName.find({_id : }).pretty()

Example: db.employees.find({_id:ObjectId(“5f20577536c73fc3e870fdb6”)}).pretty()

 db.employees.find({_id: ObjectId("5f20577536c73fc3e870fdb6")}).pretty()
{
        "_id" : ObjectId("5f20577536c73fc3e870fdb6"),
        "gender" : "female",
        "name" : {
                "title" : "mademoiselle",
                "first" : "delia",
                "last" : "durand"
        },
        "location" : {
                "street" : "6735 rue abel-hovelacque",
                "city" : "fontaines-sur-grandson",
                "state" : "appenzell ausserrhoden",
                "postcode" : 6137,
                "coordinates" : {
                        "latitude" : "-65.0877",
                        "longitude" : "-90.4049"
                },
                "timezone" : {
                        "offset" : "+2:00",
                        "description" : "Kaliningrad, South Africa"
                }
        },
        "email" : "delia.durand@example.com",
        "login" : {
                "uuid" : "6c4ea050-eca4-4809-8024-96a98f655553",
                "username" : "purplebear663",
                "password" : "sparky1",
                "salt" : "rzU1EPXV",
                "md5" : "a9198f953f34daf7b461b6065734d13b",
                "sha1" : "43c50f99742937b3ddd3f9ec0863924741b408c9",
                "sha256" : "63da5442d2a4d2ca02e0b3bb138e28760aa732258e35de102c8fd652c48721ea"
        },
        "dob" : {
                "date" : "1966-08-03T09:22:41Z",
                "age" : 52
        },
        "registered" : {
                "date" : "2009-05-28T19:09:24Z",
                "age" : 9
        },
        "phone" : "(166)-728-8912",
        "cell" : "(301)-529-4162",
        "id" : {
                "name" : "AVS",
                "value" : "756.5746.5832.39"
        },
        "picture" : {
                "large" : "https://randomuser.me/api/portraits/women/91.jpg",
                "medium" : "https://randomuser.me/api/portraits/med/women/91.jpg",
                "thumbnail" : "https://randomuser.me/api/portraits/thumb/women/91.jpg"
        },
        "nat" : "CH"
}

Mongodb findone

The findOne() method Return the single document if the filter is passed it will get the matching first document if not it will return the first document from the collection.

Command: db.collectionName.findOne()

Example: db.employees.findOne()

Mongodb find

The find() returns a cursor object that points to any documents that match the specified query filters. Using the cursor object, we can further manipulate the result.  Like limiting and sorting the data, converting the result into the array and iterates the cursor, and returns a Promise that resolves to the next document in the cursor. If the cursor is exhausted, the promise resolves to undefine.

Command: db.collectionName.find()

Example: db.employees.find()

When you run the above commands, you can see Type “it” for more at the end of the result if there is enough data. If you type it, it will fetch the next set of data from the database.

Mongodb find with limit

The limit () is used to specify the maximum number of documents to fetch in the query result set. If the result set contains more documents than the specified limit, the cursor will return documents in order up to the limit.

Remember, you can’t call limit() method after retrieving one or more documents using cursor.next() or cursor.toArray().

Command: db.collectionName.find().limti()

Example: db.employees.find().limit(5)

 > db.employees.find().limit(4)

{ "_id" : ObjectId("5f20577536c73fc3e870fda4"), "gender" : "male", "name" : { "title" : "mr", "first" : "harvey", "last" : "chambers" }, "location" : { "street" : "3287 high street", "city" : "carlow", "state" : "wexford", "postcode" : 47671, "coordinates" : { "latitude" : "-22.5329", "longitude" : "168.9462" }, "timezone" : { "offset" : "+5:00", "description" : "Ekaterinburg, Islamabad, Karachi, Tashkent" } }, "email" : "harvey.chambers@example.com", "login" : { "uuid" : "8f583f57-c999-4a5d-a8c1-d913b574c082", "username" : "greenrabbit148", "password" : "june", "salt" : "dAsaXJGK", "md5" : "e3759db2391b798ffea2cc168e1280fd", "sha1" : "a3e77fd5fdd75e3b173ceec6c3c1bbe5e83540cc", "sha256" : "7564eac1899234d5902fadfb995303a58370232f54bee6adb26e25394e2ffddd" }, "dob" : { "date" : "1988-05-27T00:14:03Z", "age" : 30 }, "registered" : { "date" : "2007-03-11T06:20:19Z", "age" : 11 }, "phone" : "061-265-5188", "cell" : "081-146-8382", "id" : { "name" : "PPS", "value" : "5608572T" }, "picture" : { "large" : "https://randomuser.me/api/portraits/men/82.jpg", "medium" : "https://randomuser.me/api/portraits/med/men/82.jpg", "thumbnail" : "https://randomuser.me/api/portraits/thumb/men/82.jpg" }, "nat" : "IE" }
{ "_id" : ObjectId("5f20577536c73fc3e870fda5"), "gender" : "male", "name" : { "title" : "mr", "first" : "victor", "last" : "pedersen" }, "location" : { "street" : "2156 stenbjergvej", "city" : "billum", "state" : "nordjylland", "postcode" : 56649, "coordinates" : { "latitude" : "-29.8113", "longitude" : "-31.0208" }, "timezone" : { "offset" : "+5:30", "description" : "Bombay, Calcutta, Madras, New Delhi" } }, "email" : "victor.pedersen@example.com", "login" : { "uuid" : "fbb3c298-2cea-4415-84d1-74233525c325", "username" : "smallbutterfly536", "password" : "down", "salt" : "iW5QrgwW", "md5" : "3cc8b8a4d69321a408cd46174e163594", "sha1" : "681c0353b34fae08422686eea190e1c09472fc1f", "sha256" : "eb5251e929c56dfd19fc597123ed6ec2d0130a2c3c1bf8fc9c2ff8f29830a3b7" }, "dob" : { "date" : "1959-02-19T23:56:23Z", "age" : 59 }, "registered" : { "date" : "2004-07-07T22:37:39Z", "age" : 14 }, "phone" : "23138213", "cell" : "30393606", "id" : { "name" : "CPR", "value" : "506102-2208" }, "picture" : { "large" : "https://randomuser.me/api/portraits/men/23.jpg", "medium" : "https://randomuser.me/api/portraits/med/men/23.jpg", "thumbnail" : "https://randomuser.me/api/portraits/thumb/men/23.jpg" }, "nat" : "DK" }
{ "_id" : ObjectId("5f20577536c73fc3e870fda6"), "gender" : "male", "name" : { "title" : "mr", "first" : "elijah", "last" : "lewis" }, "location" : { "street" : "2623 paddock way", "city" : "virginia beach", "state" : "wyoming", "postcode" : 54880, "coordinates" : { "latitude" : "-42.6128", "longitude" : "-18.5996" }, "timezone" : { "offset" : "+3:30", "description" : "Tehran" } }, "email" : "elijah.lewis@example.com", "login" : { "uuid" : "2292b7c7-a9bf-4341-abbd-c5841444ab6e", "username" : "angrygorilla267", "password" : "toonarmy", "salt" : "DUtMcvWR", "md5" : "258eaa742373ee70976d53d1b84d4764", "sha1" : "62f168f38fa3f6efbd815b58518775d3c6cf0080", "sha256" : "a4ab496047b9de7df39adbdabfecc813b8da428087029c94c2b748cef092f85e" }, "dob" : { "date" : "1986-03-29T06:40:18Z", "age" : 32 }, "registered" : { "date" : "2007-12-24T10:32:11Z", "age" : 10 }, "phone" : "(187)-486-3727", "cell" : "(986)-974-0857", "id" : { "name" : "SSN", "value" : "127-66-9786" }, "picture" : { "large" : "https://randomuser.me/api/portraits/men/57.jpg", "medium" : "https://randomuser.me/api/portraits/med/men/57.jpg", "thumbnail" : "https://randomuser.me/api/portraits/thumb/men/57.jpg" }, "nat" : "US" }
{ "_id" : ObjectId("5f20577536c73fc3e870fda7"), "gender" : "female", "name" : { "title" : "mrs", "first" : "olav", "last" : "oehme" }, "location" : { "street" : "gartenstraße 64", "city" : "nastätten", "state" : "mecklenburg-vorpommern", "postcode" : 93640, "coordinates" : { "latitude" : "-52.8348", "longitude" : "-67.5738" }, "timezone" : { "offset" : "-3:00", "description" : "Brazil, Buenos Aires, Georgetown" } }, "email" : "olav.oehme@example.com", "login" : { "uuid" : "2608c05c-8951-4aee-bcd2-f598c80f32bb", "username" : "heavypeacock371", "password" : "silent", "salt" : "E6R29k0e", "md5" : "587f4392dc06a9fb69a52eae94fd32f2", "sha1" : "82eba68b1fe2407281da5787b9b89505c663b587", "sha256" : "304034638901015d8a7b2fd43530fffc4c7d621ccfab98de935d9c8387198796" }, "dob" : { "date" : "1960-11-28T23:07:18Z", "age" : 57 }, "registered" : { "date" : "2011-05-31T00:24:05Z", "age" : 7 }, "phone" : "0748-6607336", "cell" : "0176-5787554", "id" : { "name" : "", "value" : null }, "picture" : { "large" : "https://randomuser.me/api/portraits/women/6.jpg", "medium" : "https://randomuser.me/api/portraits/med/women/6.jpg", "thumbnail" : "https://randomuser.me/api/portraits/thumb/women/6.jpg" }, "nat" : "DE" }
>

Mongodb Sort

The sort() method of the cursor is used to sorts documents in the result set according to the sorting filter. Sort documents specify one or more fields to sort on. The value of each field indicates whether MongoDB should sort it in ascending (1) or descending (-1) order.

Command: db.collectionName.find().sort({ })

Example: db.employees.find().sort({_id:-1})

Mongodb Projection

Generally, the find() or findOne() method returns the entire document with the _id. But in some scenarios, you may wish to fetch only some of the fields from the entire document. For example, from the employees, we want to fetch all the employee’s names only or we want to fetch username and password, and so on.

Here Projection helps us in filtering the output data based on the input given. So, the basic rule for applying projection is to use 1 to include any record in out and 0 to exclude.

Command: db.collectionName.find({< filter fields leave it like {} if no filter >},{})

Example: db.employees.find({},{email:1})

>
db.employees.find({},{email:1})
{ "_id" : ObjectId("5f20577536c73fc3e870fda4"), "email" : "harvey.chambers@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fda5"), "email" : "victor.pedersen@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fda6"), "email" : "elijah.lewis@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fda7"), "email" : "olav.oehme@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fda8"), "email" : "carl.jacobs@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fda9"), "email" : "madeleine.till@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdaa"), "email" : "shona.kemperman@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdab"), "email" : "louise.graham@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdac"), "email" : "zachary.lo@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdad"), "email" : "isolino.viana@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdae"), "email" : "katie.welch@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdaf"), "email" : "sandra.lorenzo@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb0"), "email" : "mestan.kaplangı@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb2"), "email" : "gideon.vandrongelen@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb3"), "email" : "maeva.wilson@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb4"), "email" : "anaëlle.adam@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb5"), "email" : "anne.ruiz@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fdb6"), "email" : "delia.durand@example.com" }
Type "it" for more

I have explained above that use 1 to apply projection to fetch only that field or fields. But here we are getting _id as well. One thing to remember is that if you don’t want _id in the result you must explicitly mention it with 0 (zero) in projection like below.

Example: db.employees.find({},{email:1,_id:0})

> db.employees.find({},{email:1,_id:0})
{ "email" : "harvey.chambers@example.com" }
{ "email" : "victor.pedersen@example.com" }
{ "email" : "elijah.lewis@example.com" }
{ "email" : "olav.oehme@example.com" }
{ "email" : "carl.jacobs@example.com" }
{ "email" : "madeleine.till@example.com" }
{ "email" : "shona.kemperman@example.com" }
{ "email" : "louise.graham@example.com" }
{ "email" : "zachary.lo@example.com" }
{ "email" : "isolino.viana@example.com" }
{ "email" : "katie.welch@example.com" }
{ "email" : "sandra.lorenzo@example.com" }
{ "email" : "mestan.kaplangı@example.com" }
{ "email" : "gideon.vandrongelen@example.com" }
{ "email" : "maeva.wilson@example.com" }
{ "email" : "anaëlle.adam@example.com" }
{ "email" : "anne.ruiz@example.com" }
{ "email" : "delia.durand@example.com" }
Type "it" for more

Mongodb find count

The count() is used to fetch the count of documents inside a collection. If a filter is passed in find() it will return count documents matched with the input filter otherwise it will return the count of all the documents.

Command: db.collectionName.find({}).count()

Example: db.employees.find({}).count()

Mongodb findone latest

To get the latest record from the database we can use _id with find() method with the help of limit (1) like below.

Command: db.collectionName.find().sort({_id:-1}).limit(1)

Example: db.employees.find().sort({_id:-1}).limit(1)

But this can hit the performance if the underlying data is huge. In such a case we can use another approach like below.

Command: db.collectionName.find().limit(1).sort({$natural:-1})

here $natural:-1 means the order opposite of the one that records are inserted in.

Example: db.employees.find().limit(1).sort({$natural:-1})

Mongodb find like

Sometimes there can be a requirement to fetch the data from MongoDB using some keywords or with the data we don’t have completely. Something like the like operator in SQL. In such cases, we can use regex to fetch the data.

Command: db.collectionName.fin({property: // })

Example: db.employees.find({email:/vand/},{email:1})

> db.employees.find({email:/vand/},{email:1})
{ "_id" : ObjectId("5f20577536c73fc3e870fdb2"), "email" : "gideon.vandrongelen@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fede"), "email" : "melvyn.vanderent@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870fee3"), "email" : "querijn.vandenboorn@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870ff31"), "email" : "vanda.novaes@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e870ffb7"), "email" : "sanjeev.vanderborgh@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710265"), "email" : "nurullah.vanderkaaden@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e87102d8"), "email" : "pedram.vandenmunckhof@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e871032e"), "email" : "warner.vandenouweland@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710397"), "email" : "hulya.vandoremalen@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e87103f6"), "email" : "solomon.vanderheijde@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710495"), "email" : "dicky.vandermaat@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e871058b"), "email" : "jonno.vanderwal@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710699"), "email" : "tulay.vanderarend@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e871087d"), "email" : "mathys.vandelft@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710a5e"), "email" : "juul.vanderhaar@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710ab8"), "email" : "nur.vandiggelen@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710b56"), "email" : "patriek.vandepeppel@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710b87"), "email" : "remy.vandegeijn@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710bb0"), "email" : "karine.vandenbos@example.com" }
{ "_id" : ObjectId("5f20577536c73fc3e8710cba"), "email" : "halil.vanduinkerken@example.com" }
Type "it" for more

This is one of the ways of using regex. You can try other regex options as well.

Mongodb find in array

While querying the data and using a filter on an array if we use db.find({tags: ‘hello’}) – it will return all the collections having array tags and the array contains a hello. But if you want to fetch only those documents which only have tags hello then we have to pass it inside the square bracket like db.find({tags [‘hello’]}).

Similarly, we can use in and not in like below.

db.find({tags : {$in : [‘hello’,’goodbye’]}}) — to use in keyword
db.find({tags : {$nin : [‘hello’,’goodbye’]}}) — to use not in keyword

Example: 

>
 db.products.find()
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ad"), "productName" : "Product 2", "price" : 199, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "winter" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ae"), "productName" : "Product 3", "price" : 399, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "monsoon" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633af"), "productName" : "Product 4", "price" : 499, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633b0"), "productName" : "Product 5", "price" : 599, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "winter" ] }


> db.products.find({usedIn: 'summer'})
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ad"), "productName" : "Product 2", "price" : 199, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "winter" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ae"), "productName" : "Product 3", "price" : 399, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "monsoon" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633af"), "productName" : "Product 4", "price" : 499, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer" ] }


> db.products.find({usedIn: ['summer']})
{ "_id" : ObjectId("5f2149f5bff8019e3cd633af"), "productName" : "Product 4", "price" : 499, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer" ] }

> db.products.find({usedIn: {$in: ['summer']}})
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ad"), "productName" : "Product 2", "price" : 199, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "winter" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ae"), "productName" : "Product 3", "price" : 399, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "monsoon" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633af"), "productName" : "Product 4", "price" : 499, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer" ] }


> db.products.find({usedIn: {$in: ['summer','mansoon']}})
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ad"), "productName" : "Product 2", "price" : 199, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "winter" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ae"), "productName" : "Product 3", "price" : 399, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "monsoon" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633af"), "productName" : "Product 4", "price" : 499, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer" ] }


> db.products.find({usedIn: {$in: ['winter','mansoon']}})
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ad"), "productName" : "Product 2", "price" : 199, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "winter" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633b0"), "productName" : "Product 5", "price" : 599, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "winter" ] }


> db.products.find({usedIn: {$nin: ['winter','mansoon']}})
{ "_id" : ObjectId("5f2149f5bff8019e3cd633ae"), "productName" : "Product 3", "price" : 399, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer", "monsoon" ] }
{ "_id" : ObjectId("5f2149f5bff8019e3cd633af"), "productName" : "Product 4", "price" : 499, "receivedOn" : ISODate("2020-07-29T10:05:41.106Z"), "usedIn" : [ "summer" ] }

Mongodb cursor to toArray

The toArray() method iterates the cursor to exhaustion and returns a Promise that resolves to an array that contains all of the iterated documents.

Command: db.collectionName.find().toArray()

Example: db.employees.find().toArray()

That’s it in this post, here we discussed various ways to fetch the data from MongoDB, how to use projection, limiting the result, sorting the data, etc.

if you are starting with MongoDB. you can check my post on Setting up MongoDB and an introduction to shell

Reference https://docs.mongodb.com/realm/mongodb/

You can share other ways to achieve the above requirements or if you know better ways to do it.

Happy Learning !!

Fundamental of MongoDB and an introduction to MongoDB CRUD operations

In this post, we will discuss the fundamentals of MongoDB and I will also introduce you to MongoDB CRUD operations with examples.

Before we head towards the CRUD operations and their example let’s understand some of the key terminologies.

key terminologies

Database: Inside a Mongo server we can have multiple databases, similar to SQL where we have multiple schemas under one database server. Inside a database, all the collections are stored.

Collection: Collection in MongoDB which holds the documents, it is similar to tables in SQL with no restricted schema.

The term no restricted schema means MongoDB does not enforce a schema to be followed by all the documents inside a particular collection, Unlike SQL where we have to define a table schema and all the records have to follow it. However, we can have schema and MongoDB allows you to validate the document against it.

Document: Document in mongodb is a single record inside a collection. The document is JSON which mogo prefers to call BSON. It is like a row in the table in terms of RDBMS.

BSON: As per wiki The name “BSON” is based on the term JSON and stands for “Binary JSON”. It is a binary form for representing simple or complex data structures including associative arrays (also known as name-value pairs), integer indexed arrays and a suite of fundamental scalar types. BSON originated in 2009 at MongoDB.

It’s time to move to the CRUD operations in MongoDB. In this section, we will discuss the following.

  • Create a database
  • Display the list of all the databases
  • The first operation of CRUD, insert record in a collection
  • Display all the collections inside a database
  • Read the document from the collection, the second operation of CRUD
  • The third operation of CRUD, update documents
  • The fourth operation of CRUD, delete documents
  • Drop collection
  • Drop database

I will use Mongo shell in this section for all the examples, if you haven’t configured it, you can read Setting up MongoDB and an introduction to Mongo shell.

Create a database

Create a database or use a database using use ‘database name’. We will create a database shop using the command, use the shop.

use shop
switched to DB shop

Display all the databases

To display all the databases we can use “show dbs” command.

show dbs
admin 0.000GB
analytics 0.003GB
config 0.000GB
local 0.000GB

Notice the shop db we have created above is not appearing here. This is because we haven’t created a single collection inside this database. No worries, let’s create one.

Insert record in a collection

db.products.insertOne({productName:'Product 1', price:299, receivedOn:new Date()})
{
"acknowledged": true,
"insertedId" : ObjectId("5ed06aa81dba2aa6bdb7a6ab")
}
> show dbs
admin 0.000GB
analytics 0.003GB
config 0.000GB
local 0.000GB
shop 0.000GB
test 0.000GB

Now you can see, after creating a document the shop db is appearing in the database list. Let’s create more documents in products collection.

db.products.insertMany([{productName:'Product 2', price:199, receivedOn:new Date()},{productName:'Product 3', price:399, receivedOn:new Date()},{productName:'Product 4', price:499, receivedOn:new Date()},{productName:'Product 5', price:599, receivedOn:new Date()}])
{
"acknowledged": true,
"insertedIds" : [
ObjectId("5ed06baf1dba2aa6bdb7a6ac"),
ObjectId("5ed06baf1dba2aa6bdb7a6ad"),
ObjectId("5ed06baf1dba2aa6bdb7a6ae"),
ObjectId("5ed06baf1dba2aa6bdb7a6af")
]
}

Display collections inside a database

To display all the collections inside a database we can “show collections” command like below.

show collections
products

Read/Fetch document from the collection

TO read documents we can use the find method like below. MongoDB also provides an aggregation framework to read the document, which will be covered in a later post.


db.products.find().pretty()
{
"_id" : ObjectId("5ed06aa81dba2aa6bdb7a6ab"),
"productName" : "Product 1",
"price" : 299,
"receivedOn" : ISODate("2020-05-29T01:51:36.729Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ac"),
"productName" : "Product 2",
"price" : 199,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ad"),
"productName" : "Product 3",
"price" : 399,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ae"),
"productName" : "Product 4",
"price" : 499,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6af"),
"productName" : "Product 5",
"price" : 599,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}

Update documents

like find and insert we can use an update method to update a document like below.

db.products.updateOne({productName:"Product 1"},{$set:{isAvailable:true}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

We can verify the update operation using the find method.

db.products.find().pretty()
{
"_id" : ObjectId("5ed06aa81dba2aa6bdb7a6ab"),
"productName" : "Product 1",
"price" : 299,
"receivedOn" : ISODate("2020-05-29T01:51:36.729Z"),
"isAvailable" : true
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ac"),
"productName" : "Product 2",
"price" : 199,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ad"),
"productName" : "Product 3",
"price" : 399,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ae"),
"productName" : "Product 4",
"price" : 499,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6af"),
"productName" : "Product 5",
"price" : 599,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}

Delete documents

Similar to update we can use the delete method to delete a document.

db.products.deleteOne({"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6af")})
{ "acknowledged" : true, "deletedCount" : 1 }

The products collection after deleting a document.
db.products.find().pretty()
{
"_id" : ObjectId("5ed06aa81dba2aa6bdb7a6ab"),
"productName" : "Product 1",
"price" : 299,
"receivedOn" : ISODate("2020-05-29T01:51:36.729Z"),
"isAvailable" : true
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ac"),
"productName" : "Product 2",
"price" : 199,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ad"),
"productName" : "Product 3",
"price" : 399,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ae"),
"productName" : "Product 4",
"price" : 499,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}

Please note, each method mentioned above to insert, read, update, and delete has multiple variations as shown in the below table.

InsertFindUpdateDelete
insertOne()findOne()updateOne()deleteOne()
insertMany()find()UpdateMany()deleteMany()
insert()findAndModify()Update()remove()
findOneAndDelete()replaceOne()
findOneAndReplace()
findOneAndUpdate()

In the next post, we will discuss all the variations in detail.

Drop collection

db.collectionName.drop()

Drop database

db.dropDatabase()

Reference

https://docs.mongodb.com/manual/reference/method/

Happy Learning !!

Setting up MongoDB and an introduction to shell

In this post, we will install MongoDB in our local machine and we will also start working with the MongoDB shell.

Will will use the community edition of MongoDB which can be downloaded from here.

The installation process is quite simple; you can follow the steps mentioned on the official website.

Once installed successfully, set the path of the installation directory till bin folder in environment variables in windows and run mongo –version from the command prompt. Successful installation will display the following information.

MongoDB shell version v4.2.6
allocator: tcmalloc
modules: none
build environment:
distmod: 2012plus
distarch: x86_64
target_arch: x86_64

Do you know, WiredTiger is the default storage engine starting in MongoDB 3.2.

Done with configuration, open command prompt, and run mongo. If mongo db is up and running you will be connected to the Mongo shell-like below.

Mongo shell

If it failed to connect to the MongoDB and display an error as below, you need to start the MongoDB manually.


MongoDB shell version v4.2.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
2020-05-28T11:41:46.879+0530 E QUERY Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: No connection could be made because the target machine actively refused it. :
connect@src/mongo/shell/mongo.js:341:17
@(connect):2:6
2020-05-28T11:41:46.882+0530 F - [main] exception: connect failed
2020-05-28T11:41:46.882+0530 E - [main] exiting with code 1

To start the Mongo go to the bin folder of the installation directory and run the mongod.exe. By default, MongoDB will create a data folder parallel to the bin folder to store the database detail.

Setting up MongoDB installation directory

However, you can specify a different folder to store both database and the logs by running the following command from the command prompt.

C:/Program Files/MongoDB/Server/4.2/bin/mongod --dbpath D:/mongodb/db --logpath D:/mongodb/logs/db.log

After running MongoDB successfully, let’s connect to the Mongo shell and get our hands dirty.

We will create a database and then we will insert some records using the following steps.

  1. Run use shop, to create a database shop. The use command will create a database if it does not exist otherwise it will return the existing one.
  2. Now run show dbs, to display the list of databases.
  3. Let’s insert our first record by running following command
  4. db.products.insertOne({name:”A book”,published:”10/11/2019″,price:300})
  5. Here products are the name of the collection to be created inside the shop database if it does not exist otherwise a new record will be inserted in the existing collection. You can verify it using the show collections command.

Here are all commands.

use shop
switched to db shop
> db.products.insertOne({name:"A book",publishedOn:"10/11/2019",price:300})
{
"acknowledged" : true,
"insertedId" : ObjectId("5ecf642b40f67acafaf1f1f4")
}

> show collections
products

Notice the highlighted text above. That is the output of the insert statement, and it returns acknowledgment true and the Id of the newly created document. You can verify it using the find command.

db.products.find().pretty()
{
"_id" : ObjectId("5ecf641640f67acafaf1f1f3"),
"name" : "A book",
"publishedOn" : "10/11/2019",
"price" : 300
}
>

That’s all in this post about MongoDB installation and introduction to Mongo shell.

Happy Learning !!