Delete Data from MongoDB

Deployment Type:
Client:

    Author: MongoDB Documentation Team

    In this guide, you will delete documents from a MongoDB database.

    Time required: 10 minutes

    What You’ll Need

    • Warning

      If you are running MongoDB locally and have not enabled authentication, your MongoDB instance is not secure.

    • Complete the Import Data into MongoDB guide so that there is data in your database to delete.

    Check Your Environment

    You will need to ensure that your MongoDB instance is running and accessible.

    Check that you have an Atlas account and have deployed a MongoDB database cluster. See Create an Atlas Account and Cluster for information on how to login and create a cluster in Atlas.

    To make sure that your MongoDB instance is running on Windows, run the following command from the Windows command prompt:

    tasklist /FI "IMAGENAME eq mongod.exe"
    

    If a mongod.exe instance is running, you will see something like:

    Image Name                     PID Session Name        Session#    Mem Usage
    ========================= ======== ================ =========== ============
    mongod.exe                    8716 Console                    1      9,508 K
    

    To make sure your MongoDB instance is running on Mac, run the following command from your terminal:

    ps -e | grep 'mongod'
    

    If a mongod instance is running, you will see something like:

    89780 ttys026    0:53.48 ./mongod
    

    To make sure your MongoDB instance is running on Linux, run the following command from your terminal:

    ps -e| grep 'mongod'
    

    If a mongod instance is running, you will see something like:

    89780 ttys026    0:53.48 ./mongod
    

    Procedure

    1

    Connect to your MongoDB instance.

    Select the operating system platform on which you are running the MongoDB client you have selected.

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo.exe <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    If you wish to manually configure your Compass connection, load Compass and select the New Connection link. You will see a form where you can enter connection information for MongoDB.

    Atlas users can copy a URI string from the Atlas console into Compass. MongoDB Compass can detect whether you have a MongoDB URI connection string in your system clipboard and auto- populate the connection dialog from the URI.

    See Set Up Atlas Connectivity for information on how to get the Atlas connection string URI into your copy buffer.

    If Compass was already running when you copied the URI string, click the NEW CONNECTION button.

    ../../_images/connect-to-host.png

    You will be prompted to populate the connection dialog. Click Yes.

    You should then populate the password field with the proper password for your MongoDB user in the connection form.

    Note

    Errors related to connecting through Compass will appear in red at the top of the Connect screen.

    It’s a good idea to put your connection code in a class so that it can be reused.

    from pymongo import MongoClient
    
    class Connect(object):
        @staticmethod    
        def get_connection():
            return MongoClient("<URISTRING>")
    

    If your connection_string starts with mongodb+srv, you need to install the dnspython module with

    python -m pip install dnspython
    

    Now add code to call the class you just created.

    from connect import Connect
    from pymongo import MongoClient
    
    connection = Connect.get_connection()
    
        final String uriString = "<URISTRING>";
        MongoClientURI uri = new MongoClientURI(uriString);
        MongoClient mongoClient = new MongoClient(uri);
    
    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    
    // Connection URL
    const url = '<URISTRING>';
    
    // Use connect method to connect to the Server
    MongoClient.connect(url, function(err, client) {
      assert.equal(null, err);
      client.close();
    });
    

    The asyncio and pprint imports will be used as you add functionality to your example code.

    import motor.motor_asyncio
    import asyncio
    import pprint
    
    client = motor.motor_asyncio.AsyncIOMotorClient('<URISTRING>')
    

    The MongoDB.Bson package is used in CRUD operations, so you’ll import it here.

    using System;
    using MongoDB.Bson;
    using MongoDB.Driver;
    
    namespace csharptest
    {
        class Connect
        {
            static void Main(string[] args)
            {
               var client = new MongoClient("<URISTRING>");
            }
        }
    }
    
    2

    Switch to the test database.

    In this guide, you will delete documents in a collection in the test database.

    To switch to the test database in the mongo shell, type

    use test
    

    If the database has not been created already, click the Create Database button.

    Screeenshot after connecting with the "Create Database" button.

    Select the test database on the left side of the Compass interface. Compass will list all of the collections in the database below the database name.

    Screenshot of the MongoDB Compass UI showing with the "test" database selected in the list of databases in the cluster.

    To access the test database:

    db = client.test
    

    Switch to the test database and access the inventory collection.

    MongoDatabase mongoDB = mongoClient.getDatabase("test");
    MongoCollection<Document> collection = mongoDB.getCollection("inventory");
    

    Within the connect block, set db to the test database.

    const db = client.db("test");
    

    To access the test database:

    db = client.test
    

    Switch to the test database and access the inventory collection.

    var database = client.GetDatabase("test");
    var collection = database.GetCollection<BsonDocument>("inventory");
    
    3

    Delete a single document.

    The following operation deletes the first document with status equal to D:

    db.inventory.deleteOne(
        { "status": "D" } // specifies the document to delete
    )
    
    1. Copy the following filter into the Compass query bar and click Find:

      { "status" : "D" }
      
    2. Click the delete icon on the first document:

      Screenshot of the MongoDB Compass UI with a filter for all documents where the "status" field value is "D". The Delete icon is moused over for the first returned document.
    3. The document will be “Flagged for Deletion”, click Delete to confirm.

      Screenshot of the MongoDB Compass UI with a filter for all documents where the "status" field value is "D". The first document is flagged for deletion with a red bar and a button to cancel or confirm the deletion.
    db.inventory.delete_one({"status": "D"})
    
    collection.deleteOne(eq("status", "D"));
    
    db.collection('inventory').deleteOne({ 
      status: "D" 
    })
    .then(function(result) {
      // process result
    })
    
    await db.inventory.delete_one({"status": "D"})
    

    For completeness, the following example shows how you might wrap the delete one operation with the asyncio event loop:

    async def do_delete_one():
        document = await db.inventory.delete_one({"status": "D"})
        pprint.pprint(document.raw_result)
    
    var filter = Builders<BsonDocument>.Filter.Eq("status", "D");
    var result = collection.DeleteOne(filter);
    

    The operation returns a document that contains the status of the operation:

    { "acknowledged" : true, "deletedCount" : 1 }
    

    The operation returns an instance of pymongo.results.DeleteResult with the status of the operation.

    The operation returns an instance of com.mongodb.client.result.DeleteResult with the status of the operation.

    The operation returns a promise that provides a result. The result.deletedCount property contains the number of documents that matched the filter.

    The operations asynchronously return instances of pymongo.results.DeleteResult with the status of the operation.

    The operation returns an instance of DeleteResult whose DeletedCount property contains the number of documents that matched the filter.

    4

    Delete multiple documents.

    The following operation deletes all of the documents in the specified inventory collection with status equal to A:

    db.inventory.deleteMany(
        { "status" : "A" } // specifies the documents to delete
    )
    
    1. Copy the following filter into the Compass query bar and click Find:

      { "status" : "A" }
      
    2. For each document, click the delete icon:

      Screenshot of the MongoDB Compass UI with a filter for all documents where the "status" field value is "A". The Delete icon is moused over for the first returned document.
    3. The document will be “Flagged for Deletion”, click Delete to confirm.

      Screenshot of the MongoDB Compass UI with a filter for all documents where the "status" field value is "D". The first document is flagged for deletion with a red bar and a button to cancel or confirm the deletion.
    db.inventory.delete_many({"status": "A"})
    
    collection.deleteMany(eq("status", "A"));
    
    db.collection('inventory').deleteMany({ 
      status: "A" 
    })
    .then(function(result) {
      // process result
    })
    
    await db.inventory.delete_many({"status": "A"})
    

    For completeness, the following example shows how you might wrap the delete many operation with the asyncio event loop:

    async def do_delete_many():
        document = await db.inventory.delete_many({"status": "A"})
        pprint.pprint(document.raw_result)
    

    Run the loop to execute both the delete_one and delete_many operations:

    loop = asyncio.get_event_loop()
    
    tasks = [
        asyncio.ensure_future(do_delete_one()),
        asyncio.ensure_future(do_delete_many()),
    ]
    
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
    
    var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
    var result = collection.DeleteMany(filter);
    

    The operation returns a document that contains the status of the operation:

    { "acknowledged" : true, "deletedCount" : 1 }
    

    The operation returns an instance of pymongo.results.DeleteResult with the status of the operation.

    The operation returns an instance of com.mongodb.client.result.DeleteResult with the status of the operation.

    The operation returns a promise that provides a result. The result.deletedCount property contains the number of documents that matched the filter.

    The operations asynchronously return instances of pymongo.results.DeleteResult with the status of the operation.

    The operation returns an instance of DeleteResult whose DeletedCount property contains the number of documents that matched the filter.

    When you are done working with your MongoDB data, close your connection to MongoDB:

    mongoClient.close();
    

    Summary

    If you have successfully completed this guide, you have deleted documents from MongoDB. That completes this introduction to CRUD operations in MongoDB.