Navigation

Delete Documents from MongoDB

Important

The MongoDB Stitch SDK is deprecated. For guidance on migrating to MongoDB Realm, please see Migrate Your App from Stitch to Realm.

Overview

The code snippets on this page demonstrate how to delete documents that are stored in a MongoDB collection. Delete operations use a query filter to specify which documents to delete.

Data Model

The examples on this page use a collection named store.items that models various items available for purchase in an online store. Each item has a name, an inventory quantity, and an array of customer reviews.

// store.items
{
    _id:      <ObjectID>,
    name:     <string>,
    quantity: <int>,
    reviews:  [ { username: <string>, comment: <string> } ]
}

Snippet Setup

To use a code snippet in a function, you must first instantiate a MongoDB collection handle:

exports = function() {
  const mongodb = context.services.get("mongodb-atlas");
  const itemsCollection = mongodb.db("store").collection("items");
  const purchasesCollection = mongodb.db("store").collection("purchases");
}

To use a code snippet in a JavaScript project, you must first do the following:

1

Import Stitch Dependencies

Import from CDN
<!-- Import the Stitch JS SDK at the top of the file -->
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch.js"></script>
<script>
  // Destructure Stitch JS SDK Components
  const { Stitch, RemoteMongoClient, BSON } = stitch;
</script>

– or –

Import from Module
// Import components of the Stitch JS SDK at the top of the file
import {
  Stitch,
  RemoteMongoClient,
  BSON
} from "mongodb-stitch-browser-sdk";
2

Instantiate a MongoDB Remote Collection Handle

const stitchApp = Stitch.initializeDefaultAppClient("<Your App ID>");
const mongodb = stitchApp.getServiceClient(RemoteMongoClient.factory, "mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");

To use a code snippet in an Android project, you must first do the following:

1

Set Up Your Project

Follow the steps in the Set up a MongoDB Mobile Project guide.

Note

For more details on setting up your Android app to use Stitch, refer to Build a Mobile App with Sync or Build a Local-Only Mobile App.

2

Import Stitch Dependencies

For CRUD operations on a remote MongoDB collection, you will use one or more of the following import statements:

// Base Stitch Packages
import com.mongodb.stitch.android.core.Stitch;
import com.mongodb.stitch.android.core.StitchAppClient;
// Stitch Authentication Packages
import com.mongodb.stitch.android.core.auth.StitchUser;
import com.mongodb.stitch.core.auth.providers.anonymous.AnonymousCredential;
// MongoDB Service Packages
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
// Utility Packages
import com.mongodb.stitch.core.internal.common.BsonUtils;

To Sync documents between a remote and a local MongoDB instance, you will also need to import the following packages:

// Stitch Sync Packages
import com.mongodb.stitch.core.services.mongodb.remote.sync.ChangeEventListener;
import com.mongodb.stitch.core.services.mongodb.remote.sync.DefaultSyncConflictResolvers;
import com.mongodb.stitch.core.services.mongodb.remote.sync.ErrorListener;
import com.mongodb.stitch.core.services.mongodb.remote.sync.internal.ChangeEvent;

Important

If you use Sync, be sure to add .sync() before every remote database call in the examples below, as in the following:

itemsCollections.sync().find()

To perform CRUD operations only on the local (on-device) database, import the following packages:

// MongoDB Mobile Local Database Packages
import com.mongodb.stitch.android.services.mongodb.local.LocalMongoDbService;
3

Instantiate a MongoDB Collection Handle

Top of Activity File
private StitchAppClient stitchClient;
private RemoteMongoClient mongoClient;
private RemoteMongoCollection itemsCollection;
In Activity.onCreate()
stitchClient = Stitch.getDefaultAppClient();
mongoClient = stitchClient.getServiceClient(RemoteMongoClient.factory, "mongodb-atlas");
itemsCollection = mongoClient.getDatabase("store").getCollection("items");
purchasesCollection = mongoClient.getDatabase("store").getCollection("purchases");

To use a code snippet in an iOS project, you must first do the following:

1

Set Up Your Project

Follow the steps in the Set up a MongoDB Mobile Project guide.

2

Import Stitch Dependencies

In scope (e.g. UIViewController)
import StitchCore
import StitchCoreRemoteMongoDBService
import StitchRemoteMongoDBService
3

Initialize the MongoDB Stitch iOS SDK

Application Startup (e.g. AppDelegate.didFinishLaunchingWithOptions())
do {
    let _ = try Stitch.initializeDefaultAppClient(
        withClientAppID: "YOUR-APP-ID"
    )
} catch {
    print("Failed to initialize MongoDB Stitch iOS SDK: \(error)")
}
4

Instantiate a MongoDB Collection Handle

In scope (e.g. UIViewController)
// Variables in scope:
private lazy var stitchClient = Stitch.defaultAppClient!
private var mongoClient: RemoteMongoClient?
private var itemsCollection: RemoteMongoCollection<Document>?

// Set the stitch variables declared above in viewDidLoad()
mongoClient = stitchClient.serviceClient(
    fromFactory: remoteMongoClientFactory,
    withName: "mongodb-atlas"
)
itemsCollection = mongoClient?.db("store").collection("items")
purchasesCollection = mongoClient?.db("store").collection("purchases")

Methods

Delete a Single Document

You can delete a single document from a collection using the collection.deleteOne() action.

The following snippet deletes one document in the items collection that has a name value of legos:

const query = { "name": "legos" };

itemsCollection.deleteOne(query)
  .then(result => console.log(`Deleted ${result.deletedCount} item.`))
  .catch(err => console.error(`Delete failed with error: ${err}`))
const query = { "name": "legos" };

itemsCollection.deleteOne(query)
  .then(result => console.log(`Deleted ${result.deletedCount} item.`))
  .catch(err => console.error(`Delete failed with error: ${err}`))
Document filterDoc = new Document().append("name", "legos");

final Task<RemoteDeleteResult> deleteTask = itemsCollection.deleteOne(filterDoc);
deleteTask.addOnCompleteListener(new OnCompleteListener <RemoteDeleteResult> () {
    @Override
    public void onComplete(@NonNull Task <RemoteDeleteResult> task) {
        if (task.isSuccessful()) {
            long numDeleted = task.getResult().getDeletedCount();
            Log.d("app", String.format("successfully deleted %d documents", numDeleted));
        } else {
            Log.e("app", "failed to delete document with: ", task.getException());
        }
    }
});
let query : Document = ["name": "legos"];

itemsCollection?.deleteOne(query) { result in
    switch result {
    case .success(let result):
        print("Deleted \(result.deletedCount) item.");
    case .failure(let error):
        print("Delete failed with error: \(error)");
    }
}

Delete One or More Documents

You can delete multiple items from a collection using the collection.deleteMany() action.

The following snippet deletes all documents in the items collection that do not have any reviews:

const query = { "reviews": { "$size": 0 } };

itemsCollection.deleteMany(query)
  .then(result => console.log(`Deleted ${result.deletedCount} item(s).`))
  .catch(err => console.error(`Delete failed with error: ${err}`))
const query = { "reviews": { "$size": 0 } };

itemsCollection.deleteMany(query)
  .then(result => console.log(`Deleted ${result.deletedCount} item(s).`))
  .catch(err => console.error(`Delete failed with error: ${err}`))
Document filterDoc = new Document().append("reviews", new Document().append("$size", 0));

final Task <RemoteDeleteResult> deleteTask = itemsCollection.deleteMany(filterDoc);
deleteTask.addOnCompleteListener(new OnCompleteListener <RemoteDeleteResult> () {
    @Override
    public void onComplete(@NonNull Task <RemoteDeleteResult> task) {
        if (task.isSuccessful()) {
            long numDeleted = task.getResult().getDeletedCount();
            Log.d("app", String.format("successfully deleted %d documents", numDeleted));
        } else {
            Log.e("app", "failed to delete document with: ", task.getException());
        }
    }
});
let query : Document = ["reviews": ["$size": 0] as Document];

itemsCollection?.deleteMany(query) { result in
    switch result {
    case .success(let result):
        print("Deleted \(result.deletedCount) item(s).");
    case .failure(let error):
        print("Delete failed with error: \(error)");
    }
}