MongoDB Commands with Examples

In post summarize the useful MongoDB commands with examples used in this MongoDB tutorial.

Show All Databases

Use the below command to get a list of all databases:
> show dbs
Example:
> show dbs
local     0.78125GB
test      0.23012GB

MongoDB Create Database

MongoDB use DATABASE_NAME is used to create a database. The command will create a new database if it doesn't exist, otherwise, it will return the existing database.

Syntax

The basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME

Example

If you want to use a database with name, then use DATABASE statement would be as follows −
> use mydb
switched to db mydb
To check your currently selected database, use the command db:
> db
mydb

MongoDB Drop Database

MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax

The basic syntax of dropDatabase() command is as follows −
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete the default 'test' database.

Example

Now, let's drop this database with dropDatabase() command:
> db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }

MongoDB Create Collection

MongoDB db.createCollection(name, options) is used to create collection.

Syntax

Basic syntax of createCollection() command:
db.createCollection(name, options)
In the command, name is the name of the collection to be created. Options are a document and are used to specify the configuration of collection.

Examples

> db.createCollection("mycollection")
{ "ok" : 1 }
You can check the created collection by using the command show collections.
> show collections
mycollection

MongoDB Drop Collection

MongoDB's db.collection.drop() is used to drop a collection from the database.

Syntax

The basic syntax of drop() command is as follows −
db.COLLECTION_NAME.drop()

Example

First, check the available collections into your database mydb.
> show collections
mycollection
posts
Now drop the collection with the name mycollection.
> db.mycollection.drop()
true
Again check the list of collections into the database.
> show collections
posts

Insert a Single Document

db.collection.insertOne() inserts a single document into a collection.
The following example inserts a new document into the posts collection. If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document.
> db.posts.insertOne({
    title: 'MongoDB Overview',
    description: 'MongoDB is no sql database',
    by: 'Java Guides',
    url: 'https://www.javaguides.net',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 500
 });
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5e1823977695f4d696a05984")
}
insertOne() returns a document that includes the newly inserted document’s _id field value.
Here "posts" is our collection name. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert a document into it.

Insert Multiple Documents

db.collection.insertMany() can insert multiple documents into a collection. Pass an array of documents to the method.
The following example inserts two new documents into the posts collection. If the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document.
db.posts.insertMany([
   {
      title: 'MongoDB Overview', 
      description: 'MongoDB is no sql database',
      by: 'Java Guides',
      url: 'https://javaguides.net',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 100
   },
 
   {
      title: 'NoSQL Database', 
      description: "NoSQL database doesn't have tables",
       by: 'Java Guides',
      url: 'https://javaguides.net',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 20, 
      comments: [ 
         {
            user:'user1',
            message: 'My first comment',
            dateCreated: new Date(2013,11,10,2,35),
            like: 0 
         }
      ]
   }
]);

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5e18246f7695f4d696a05985"),
                ObjectId("5e18246f7695f4d696a05986")
        ]
}
insertMany() returns a document that includes the newly inserted documents _id field values. See the reference for an example.

MongoDB Query Document

To query data from MongoDB collection, you need to use MongoDB's find() method.

Syntax

The basic syntax of the find() method is as follows −
> db.COLLECTION_NAME.find()
find() method will display all the documents in a non-structured way.

Example

> db.posts.find( {} );
{ "_id" : ObjectId("5e1840697695f4d696a05987"), "title" : "MongoDB Overview", "description" : "MongoDB is no sql database", "by" : "Java Guides", "url" : "https://javaguides.net", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5e1840697695f4d696a05988"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "Java Guides", "url" : "https://javaguides.net", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-10T09:35:00Z"), "like" : 0 } ] }

Pretty print Documents

To display the results in a formatted way, you can use the pretty() method.

Syntax

> db.posts.find().pretty()

Example

> db.posts.find().pretty()
{
        "_id" : ObjectId("5e1840697695f4d696a05987"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5e1840697695f4d696a05988"),
        "title" : "NoSQL Database",
        "description" : "NoSQL database doesn't have tables",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}

Update Documents in a Collection

Update a Single Document

The following example uses db.collection.updateOne() method on the posts collection to update the first document where title equals "MongoDB Overview":
db.posts.updateOne(
   { title : "MongoDB Overview" },
   {
     $set: { "by": "Ramesh", description: "MongoDB is no sql database and document oriented database" }
   }
)
The update operation uses the $set operator to update the value of the by field to "Ramesh" and the value of the description field to "MongoDB is no sql database and document oriented database".

Update Multiple Documents

The following example uses the db.collection.updateMany() method on the posts collection to update all documents where by field equal to ""https://javaguides.net":
db.posts.updateMany(
   { "likes": { $lt: 50 } },
   {
     $set: { "title": "MongoDB NoSQL Database" }
   }
);

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Replace a Document

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to db.collection.replaceOne().
The following example replaces the first document from the inventory collection where by: "Ramesh":
db.posts.replaceOne(
   { by: "Ramesh" },
   {
        "title" : "MongoDB Architecture",
        "description" : "MongoDB Architecture",
        "by" : "Ramesh",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100,
        "lastModified" : ISODate("2020-01-10T09:26:39.709Z")
   }
)

Delete All Documents

To delete all documents from a collection, pass an empty filter document {} to the db.collection.deleteMany() method.
The following example deletes all documents from the inventory collection:
db.posts.deleteMany({})

Delete Only One Document that Matches a Condition

To delete at most a single document that matches a specified filter (even though multiple documents may match the specified filter) use the db.collection.deleteOne() method.
The following example deletes the first document where the title is "MongoDB Overview":
db.posts.deleteOne( { title: "MongoDB Overview" } )

Delete All Documents that Match a Condition

You can specify criteria, or filters, that identify the documents to delete. The filters use the same syntax as read operations.
The following example removes all documents from the inventory collection where the by field equals "Java Guides":
db.inventory.deleteMany({ by : "Java Guides" })

MongoDB Projection

The following example will display the title and description of the document while querying the document.
> db.posts.find({},{"title":1,description:1}).pretty();
{
        "_id" : ObjectId("5e184a067695f4d696a0598d"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database"
}
{
        "_id" : ObjectId("5e184a067695f4d696a0598e"),
        "title" : "NoSQL Database",
        "description" : "NoSQL database doesn't have tables"
}
If you want to retrieve the only title of the posts then use the following query:
> db.posts.find({},{"title":1}).pretty();
{
        "_id" : ObjectId("5e184a067695f4d696a0598d"),
        "title" : "MongoDB Overview"
}
{ "_id" : ObjectId("5e184a067695f4d696a0598e"), "title" : "NoSQL Database" }

The Limit() Method

To limit the records in MongoDB, you need to use a limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.

Syntax

The basic syntax of the limit() method is as follows −
> db.COLLECTION_NAME.find().limit(NUMBER)
The following example will display only two documents while querying the document.
> db.posts.find({},{"title":1,_id:0}).limit(2);
{ "title" : "MongoDB Overview" }
{ "title" : "NoSQL Database" }

MongoDB Sorting

To sort documents in MongoDB, you need to use the sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Syntax

The basic syntax of the sort() method is as follows −
> db.COLLECTION_NAME.find().sort({KEY:1})

Example

The following example will display the documents sorted by title in the descending order.
> db.posts.find({},{"title":1,_id:0}).sort({"title":-1});
{ "title" : "NoSQL Database" }
{ "title" : "MongoDB Overview" }
{ "title" : "MongoDB CRUD Operations" }

References

Comments