Tutorialspoint

1 Answer
Nishtha Thakur

If you will try to use the method drop(), then it will delete all information about the collection. Indexing is fast. However, if you will use the method remove(), then it removes all records but keeps the collection and indexes.

Let us check with the help of example.

Using drop()

Let us first create a collection with documents −

> db.dropWorkingDemo.createIndex({"FirstName":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

> db.dropWorkingDemo.insertOne({"FirstName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdd8742bf3115999ed511e9")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.dropWorkingDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cdd8742bf3115999ed511e9"), "FirstName" : "John" }

Now, I am going to use drop() −

> db.dropWorkingDemo.drop();

This will produce the following output −

True

Let us check the indexes is present after using the drop() method or not −

> db.dropWorkingDemo.getIndexes();

This will produce the following output −

[ ]

Indexes are not present.

Using remove()

We will now check the method remove(). Let us first create a collection with documents −

> db.removeDemo.createIndex({"FirstName":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.removeDemo.insertOne({"FirstName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdd8868bf3115999ed511ea")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.removeDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cdd8868bf3115999ed511ea"), "FirstName" : "John" }

Let us use remove() −

> db.removeDemo.remove({});
WriteResult({ "nRemoved" : 1 })

After using remove() method, let us check the indexes are present or not −

> db.removeDemo.getIndexes();

This will produce the following output −

[
   {
      "v" : 2,
      "key" : {
         "_id" : 1
      },
      "name" : "_id_",
      "ns" : "test.removeDemo"
   },
   {
      "v" : 2,
      "key" : {
         "FirstName" : 1
      },
      "name" : "FirstName_1",
      "ns" : "test.removeDemo"
   }
]

Yes, index is present.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.