Open In App

MongoDB Queries Document

Last Updated : 16 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB is NoSQL(Not only SQL) database because the storage and retrieval of data in MongoDB are not in the form of tables like in SQL. It stores data in a BSON structure. It uses BSON or Binary JSON data format to organize and store data. This data format includes all JSON data types and adds types for dates, different size integers, ObjectIds, and binary data. In MongoDB, a database is a physical container for the collections. It contains one or more collections. A MongoDB server has multiple databases inside it. A database stores data in the collection. A collection is a group of one or more documents that exists within a single database. A single collection contains different types of documents, which means if one document contains 10 fields then another document within the same collection may contain 20 fields. In this article, we will discuss the basic concept of MongoDB servers like databases, collections and documents and will mainly focus on MongoDB’s Basic Queries of Database and Collection with the help of examples. This article will give you a quick start with MongoDB and make you comfortable with MongoDB Queries.

SHOW Statement

It is used to show all the databases present in the MongoDB server. It will not show you the newly created database until you add a collection to it. If you want to check the currently selected database then you can use db command.

Syntax:

show databases;

Example:

When you run the show databases command then it will show you all the databases present in MongoDB except databases that don’t have any collection. In this example, company, myDatabase, test, and university are the user-defined databases, and admin, config, and local are built-in databases. One collection is important to insert into the database to display in the show databases command. 

Show-database

 

 

DB Statement

It is used to show the currently selected database. If the database doesn’t contain any collection then the show databases command will not show that database in the list. So, to check which database we are using you need to use this command.

Syntax:

db;

Example:

In this example, we have created one database named university by using the use command. After that, we run the show databases command to check the list of databases in the MongoDb but there is no university database present in the MongoDB. The reason is university database doesn’t contain any collection. So, to check the currently selected database use the db command. 

using-db-command

 

USE Statement

It is used to create the new database and switch to that if the database does not exist in the MongoDB server or if the database exists then use command switches to the existing database.

Note: After creating a new database if you will do show databases then it will not show you the newly created database until you add a collection to it. If you want to check the currently selected database then you can use db command.

Syntax:

use <database_name>;

<database_name> is the name of the database. The database name should satisfy the naming convention of the MongoDB server database name. 

Example:

use university;

In this example, we have created one new database named university by using the use command. It will also switch to the university database. You can check the currently selected database by using db command and you will get university in this example.

Using-the-use-statement

 

DROP Statement

It is used to drop/remove the database from MongoDB. To remove the database first you have to switch to the database which you want to drop by using the use command and then calling the dropDatabase() method on the selected database. 

Syntax:

use <database-name>;
db;
db.dropDatabase();

Example: 

use university;
db;
db.dropDatabase();

In this example, we are using the use command to switch to the database which we want to remove from the MongoDb server. After using the use command, check the current database to make sure that the database is switched properly by using db command. After you switched to the database, use dropDatabase() method on the selected database.

Drop-statement

 

SHOW Statement

It is used to show all the collections present in the selected database. 

Syntax: 

db;
show collections;

Example:

Here, we first select the database whose collections list you want to check by using db command and then run show collections command to check the list of the collection present in the selected database.

Show-collection

 

CREATE Statement

This statement is used to create a collection within the selected database. createCollection() method will take the name of the collection as an argument. The collection name should not be a null or empty string, otherwise, it will throw an error.  

Syntax:

db.createCollection(“<name_of_collection>”);

<name_of_collection> is the name of the collection. The collection name should satisfy the naming convention of the MongoDB collection name. 

Example:

 db.createCollection(“teacher_contact_details”);

In this example, we are creating the teacher_contact_details collection. Firstly, run the use command to switch to the university database in which we want to insert the collection. Then check the selected database by using db command. After that, call createCollection() method on the selected database and pass the collection name as an argument. To check whether the collection is inserted or not in the database run the show collections command.

Using-create-statement

 

DROP Statement

It is used to drop/remove the collection from the selected database. It will also removes any indexes associated with the dropped collection. To remove any collection from the selected database, call drop() method on that collection. If the collection is present in the database and it will be deleted successfully then it will return true. If the collection is not present in the database then it will return false.

Syntax:

db.<collection_name>.drop();

Example:

db.teacher_contact_details.drop();

In this example, we are dropping the collection named teacher_contact_details. Firstly, we run the use command to switch to the university database and then check whether the database is switched or not by using db command. After that, we use show collections command to check the list of the collections and then call the drop() method on the teacher_contact_details  collection. It returns true means collection, as well as all indexes associated with it, are successfully deleted.

Drop-collection

 

Find The Documents

It is used to find all the documents that satisfy the specified criteria in the selected collection.   

Syntax:

db.<collection_name>.find(<filter>, <projection>);

  • <filter>  is a selection criterion used to select the documents. If we want all the documents in the selected collection then either omit the filter parameter or pass an empty document ({}).    
  • <projection> is used to select specific fields from the collection to include them in the output document. To include the field use 1. ‘ _id’ is always included in the output document so to exclude it use _id : 0. 

Note: Projection is used to improve the performance by optimizing the query. It reduces the fields in the document.

Example: 

In the following example, we are using the find() method with no parameters that return all documents from a collection and return all fields of the documents. The following operation returns all the documents in the ’employee_details’ collection which is present in the company database.

db.employee_details.find();  or  db.employee_details.find({});

Using-find-method

 

Find First Document

It is used to find the first document that satisfies the specified criteria on the selected collection.  It only returns the first document in the collection if we have more than one documents that match the specified criteria.

Syntax:

db.<collection_name>.findOne(<filter>, <projection>);

  • <filter> is a selection criterion used to select the document. If we pass an empty document ({}) as a filter then this method will return the first document in the collection.
  • <projection> is used to select specific fields from the collection to include them in the output document. To include the field use 1. ‘ _id’ is always included in the output document so to exclude it use _id : 0. 

Example:

In the following example, we are using the findOne() method with no parameters that return the first document from the collection and returns all fields of the document.

db.employee_details.findOne() or  db.employee_details.findOne({});

Using-findOne-method

 

Find And Replace Document

It is used to replace the first document that satisfies the given criteria with the given replacement document. It is not used to update the fields. By default, it will return the original document. For returning the replacement document, set option ‘returnNewDocument : true’ in option section.

Syntax:

db.<collection_name>.findOneAndReplace(
       <filter>,
       <replacement> ,
       <option>
);

  • <filter> is a selection criterion used to select the document. If we pass an empty document ({}) as a filter then this method will replace the first document in the collection.
  • <replacement> is a replacement document that replaces the first document that is selected by matching the specified filter.
  • <option> is optional.

Example:

In the following example, we are using the findOneAndReplace() method which is used to replace the document that matches the specified filter with the replacement document.

db.employee_details.findOneAndReplace(
   {“salary” : 30000}, 
   { “salary” : 40000, 
      “name”: {“firstName” : “Rohit”, “lastName” : “Khurana”},
   }
);

  • {“salary” : 30000}  is the filter argument that matches the document to replace.
  • { “salary” : 40000,  “name”: {“firstName” : “Rohit”, “lastName” : “Khurana”} } is the replacement document.
  • The following operation matches the document where salary field equals to 30000 from the ’employee_details’ collection and replaces this document with { “salary” : 40000,  “name”: {“firstName” : “Rohit”, “lastName” : “Khurana”} }. It returns the original document.

The following is the document after replacement:

{

  “_id”: {

    “$oid”: “629f87d1863729e229a35887”

  },

  “salary”: 40000,

  “name”: {

    “firstName”: “Rohit”,

    “lastName”: “Khurana”

  }

}

Using-findOneAndReplace()-method

 

Find And Delete Document

It is used to delete the first document that matches the specified filter. It returns the deleted document if the match is found otherwise returns null.

Syntax:

db.<collection_name>.findOneAndDelete(
      <filter> ,
     <option>
)

Here, <filter> is a selection criterion used to select the document. If we pass an empty document ({}) as a filter then this method will delete the first document in the collection.

Example:

In the following example, we are using the findOneAndDelete() method which is used to delete the first document that matches the specified filter.

db.employee_details.findOneAndDelete({“name.firstName” : “Rohit”});

  • {“name.firstName” : “Rohit”}  is the filter argument that matches the document to delete.
  • The following operation selects the document where ‘name.firstName’ field equals ‘Rohit’ from the ’employee_details’ collection and then deletes this document. It returns the deleted document. 
Using-findOneAndDelete-method

 

Find And Update Document

It is used to update the first document that matches the given filter. It returns the original document. By default, it will returns the original document. For returning the updated document, set option ‘returnNewDocument : true’ in option section.

Syntax: 

db.Students.findOneAndUpdate(
            <filter> , 
            <update>,
            <option>
)

  • <filter> is a selection criterion used to select the document. If we pass an empty document ({}) as a filter then this method will update the first document in the collection.
  • <update> is a update document or aggregation pipeline.
  • <option> is optional

Example: 

In the following example, we are using the findOneAndUpdate() method which is used to update the document that matches the specified filter.

  •  {“name.firstName” : “Romal”} is the filter argument that matches the document to update.
  • The {$set: {“address.phone.number” : 9876543210, “salary” : 80000} } specifies the change to apply. It uses the $set operator to set the value of the ‘address.phone.number’ field (Embedded Document) to ‘9876543210’ and ‘salary’ field to ‘80000’
  • The following operation selects the document where ‘name.firstName’ field equals ‘Romal’ from the ’employee_details’ collection and then updates this document. It returns the original document.

db.employee_details.findOneAndUpdate(
   {“name.firstName” : “Romal” }, 
  {$set: {“address.phone.number” : 9876543210 , “salary” : 80000}
  }
)

The following is the updated document.

{

 “_id”: {

   “$oid”: “629118c67017e180fa9ff11e”

 },

 “name”: {

   “firstName”: “Romal”,

   “lastName”: “Singla”

 },

 “address”: {

   “phone”: {

     “type”: “Home”,

     “number”: 9876543210

   }

 },

 “salary”: 80000,

 “doj”: {

   “$date”: “2022-05-26T18:30:00Z”

 },

 “skills”: [

   “React”,

   “MongoDB”,

   “Javascript”

 ]

}

Using-findOneAndUpdate-method

 

Delete One Document

It is used to delete the first document that matches the filter. It only deletes the first document in the collection if we have more than one documents that match the specified criteria.

Syntax : 

db.<collection_name>.deleteOne(<filter>);

Here, <filter> is a document that specifies the criteria for the deletion. If the filter matches more than one document, then the deleteOne() method deletes only the first document.

Example: 

In the following example, we use the deleteOne() method to delete the document where “name.firstName” is “Rohit”. The {“name.firstName” : “Rohit”} is the filter argument that matches the documents to delete. In this example, it matches the document whose name.firstName (Embedded Document) is “Rohit”.

db.employee_details.deleteOne({“name.firstName” : “Rohit”}); 

The above operation returns the following document. Here, deletedCount containing the number of deleted documents

{ “acknowledged” : true, “deletedCount” : 1 }

Using-deleteOne-method

 

Delete Many Documents

It is used to delete all the documents from the collection that matches the filter. If we pass an empty document ({}) then deleteMany() method removes all the documents from the collection. Please be careful while using this method.

Syntax: 

db.<collection_name>.deleteMany(<filter>)

Here <filter> is a document that specifies the condition to select the document for deletion. If you pass an empty document ({}) into the deleteMany() method, it will delete all the documents from the selected collection.

Example: 

In the following example, we use the deleteMany() method to delete all the documents that contain salary: 30000. The {“salary” : 30000 } is the filter argument that matches the documents to delete. In this example, it matches all the documents whose ‘salary’ :  30000.

db.employee_details.deleteMany({“salary” : 30000}); 

The above operation returns the following document. Here, deletedCount contains the number of deleted documents.

{ “acknowledged” : true, “deletedCount” : 3 }

Using-deleteMany-method

 

Insert one document

It is used to insert one document inside the collection. It calls insertOne() method on collection in which we want to insert the document. If the collection does not exist, then the insertOne() method creates the collection.
Here, insertOne() method takes a document as an argument that is in BSON data format.

Syntax: 

db.<collection_name>.insertOne(<document>);

Example: 

In this example, we are creating one document by using insertOne() method with 5 fields named name, address, salary, doj, skills. The name holds object type, address holds document (Embedded Documents), salary holds number, doj holds date type, skills holds array type. This document doesn’t hold ‘_id’ field So, MongoDB creates and adds the ‘_id’ key and assigns it a unique ObjectId() value.

 db.employee_details.insertOne(
       {
           “name”: {“firstName” : “Rohit”, “lastName” : “Singla”},
           “address”: {
                phone: { type: “Home”, number: “000-000-000-7” }
          },
        “salary”: 30000.00,
        “doj”: new Date(’27 May 2022′),
       “skills” : [“React”, “MongoDB”, “Javascript” ]
    }
);

The above operation returns the following document:

{
       “acknowledged” : true,
       “insertedId” : ObjectId(“62911cfe7017e180fa9ff122”);
}

Using-insertOne-method

 

Insert multiple documents

It is used to insert multiple documents inside the collection. It calls insertMany() method on collection in which we want to insert the documents. Here, insertMany() method takes an array of documents as an argument which is in BSON data format.

Syntax: 

db.<collection_name>.insertMany(
      [
       <document1>, <document2>, …
     ]
);

Example:

In this example, we are creating two documents by using insertMany() method with 5 fields named city, state, country, pincode.
This document doesn’t hold ‘_id’ field So, MongoDB creates and adds the ‘_id’ key and assigns it a unique ObjectId() value.

db.employee_details_contact.insertMany( 
         [
           { 
              “city”: “Hisar”, “state”: “Haryana”, 
             “country” : “India” , “pincode” : “656565”
           },
           { 
               “city”: “Gurgaon”, “state”: “Haryana”, 
              “country” : “India” , “pincode” : “345678”
            },
        ]
);

The above operation returns the following document:

{
       “acknowledged” : true,
       “insertedIds” : [
               ObjectId(“629211cf7017e180fa9ff123”),
               ObjectId(“629211cf7017e180fa9ff124”)
       ]
}

Using-insertMany-method

 

Update Document

It is used to modify the document or documents in the collection which satisfy the filter. This can update the existing document, completely replace the existing document or also add a new document to the collection. By using multi:true option, it can update all the documents which satisfies condition like updateMany() method.

Syntax: 

db.<collection_name>.update(
        <filter>,
      <update>
)

  • The <filter>  is a document that specifies the criteria for the update.
  • The <update> is a document that specifies the change to apply.

Example: 

In the following example, we use the update() method to update the field ‘address.phone.number’ of the document where “name.firstName” is “Rohit”.

  • The {“name.firstName” : “Rohit”} is the filter argument that matches the documents to update. In this example, it matches the document whose name.firstName (Embedded Document) is “Rohit”.
  • The {$set : {“address.phone.number” : “111-111-111-8”} } specifies the change to apply. It uses the $set operator to set the value of the ‘address.phone.number’ field (Embedded Document) to “111-111-111-8”.

db.employee_details.update(
      {“name.firstName” : “Rohit”},
      {
           $set : {“address.phone.number” : “111-111-111-8”}
       }
  )

The above operation returns the following output, matchedCount indicates the number of documents that matched the criteria, and modifiedCount indicates the number of documents updated.

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

Using-update-method

 

Update One Document

It is used to update a single document. It only updates the first document in the collection if we have more than one documents that match the specified criteria.

Syntax: 

db.<collection_name>.updateOne(
         <filter>
       <update>
)

  • <filter> is a document that specifies the criteria for the update. If the filter matches more than one document, then the updateOne() method updates only the first document. If you pass an empty document {} into the method, it will only update the first document of the collection. 
  • <update> is a document that specifies the updates to apply.

Example: 

In the following example, we use the updateOne() method to update the field pincode of the document with _id: 1. The updateOne() method will always modify a single document.

  • The { _id : 1 } is the filter argument that matches the documents to update. In this example, it matches the document whose _id is 1.
  • The { $set : {“pincode” : “1111111”} } specifies the change to apply. It uses the $set operator to set the value of the pincode field to 1111111.

db.employee_details_contact.updateOne(
           {“_id” : 1},
           {
              $set : {“pincode” : “1111111”}
           }
   )

The above operation returns the following output, matchedCount indicates the number of documents that matched the criteria, and modifiedCount indicates the number of documents updated.

{ “acknowledged” : true, “matchedCount” : 1, “modifiedCount” : 1 }

Using-updateOne-method

 

Update Many documents

It is used to update all the documents in the collection that matches the specified criteria. This is similar to the update method when we use ‘multi : true’ option.

Syntax:

db.<collection_name>.updateMany(
        <filter>
       <update>
)

  • <filter> is a document that specifies the condition to select the document for update. If you pass an empty document ({}) into the updateMany() method, it will update all the documents.
  • <update> is a document that specifies the updates to apply.

Example: 

In the following example, we use the updateMany() method to update the field salary of the document with salary: 20000. This method is used to update all the documents which satisfy the specified criteria.

  • The  {“salary”:20000 } is the filter argument that matches the documents to update. In this example, it matches all the documents whose ‘salary’ :  20000.
  • The { $set: {“salary”:85000 } } specifies the change to apply. It uses the $set operator to set the value of the salary field to 85000.

db.employee_details.updateMany(
           {“salary”:20000 }, 
           { 
             $set: {“salary”:85000 }
           }

The above operation returns the following output, matchedCount indicates the number of documents that matched the criteria, and modifiedCount indicates the number of documents updated.

{ “acknowledged” : true, “matchedCount” : 5, “modifiedCount” : 5 }

Using-updateMany-method

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads