Navigation

Add Data to MongoDB

Overview

The code snippets on this page demonstrate how to insert one or more documents into a MongoDB collection. Insert operations take the documents to add to MongoDB as an argument and return documents that describe the results of the operation.

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

Insert a Single Document

You can insert a single document using the collection.insertOne() action.

The following snippet inserts a single item document into the items collection:

const newItem = {
  "name": "Plastic Bricks",
  "quantity": 10,
  "category": "toys",
  "reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};

itemsCollection.insertOne(newItem)
  .then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
  .catch(err => console.error(`Failed to insert item: ${err}`))
const newItem = {
  "name": "Plastic Bricks",
  "quantity": 10,
  "category": "toys",
  "reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};

itemsCollection.insertOne(newItem)
  .then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
  .catch(err => console.error(`Failed to insert item: ${err}`))
Document newItem = new Document()
    .append("name", "legos")
    .append("quantity", 10)
    .append("category", "toys")
    .append("reviews", Arrays.asList(
        new Document()
        .append("username", "mongolover")
        .append("comment", "this is great")
    ));


final Task <RemoteInsertOneResult> insertTask = itemsCollection.insertOne(newItem);
insertTask.addOnCompleteListener(new OnCompleteListener <RemoteInsertOneResult> () {
    @Override
    public void onComplete(@NonNull Task <RemoteInsertOneResult> task) {
        if (task.isSuccessful()) {
            Log.d("app", String.format("successfully inserted item with id %s",
                task.getResult().getInsertedId()));
        } else {
            Log.e("app", "failed to insert document with: ", task.getException());
        }
    }
});
let newItem: Document = [
    "name": "Plastic Bricks",
    "quantity": 10,
    "category": "toys",
    "reviews": [
        [
            "username": "legolover",
            "comment": "These are awesome!"
        ] as Document
    ],
];

itemsCollection?.insertOne(newItem) { result in
    switch result {
    case .success(let result):
        print("Successfully inserted item with _id: \(result.insertedId))");
    case .failure(let error):
        print("Failed to insert item: \(error)");
    }
}

Insert One or More Documents

You can insert multiple documents at the same time using the collection.insertMany() action.

The following snippet inserts multiple item documents into the items collection:

const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football",   "category": "sports", "quantity": 30, "reviews": [] };

return itemsCollection.insertMany([doc1, doc2])
  .then(result => {
    console.log(`Successfully inserted ${result.insertedIds.length} items!`);
    return result
  })
  .catch(err => console.error(`Failed to insert documents: ${err}`))
const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football",   "category": "sports", "quantity": 30, "reviews": [] };

itemsCollection.insertMany([doc1, doc2])
  .then(result => {
    console.log(`Successfully inserted ${result.insertedIds.length} items!`);
  })
  .catch(err => console.error(`Failed to insert documents: ${err}`))
Document doc1 = new Document()
    .append("name", "basketball")
    .append("category", "sports")
    .append("quantity", 20)
    .append("reviews", Arrays.asList());

Document doc2 = new Document()
    .append("name", "football")
    .append("category", "sports")
    .append("quantity", 30)
    .append("reviews", Arrays.asList());

List<Document> docs = Arrays.asList(doc1, doc2);

final Task <RemoteInsertManyResult> insertTask = itemsCollection.insertMany(docs);
insertTask.addOnCompleteListener(new OnCompleteListener <RemoteInsertManyResult> () {
    @Override
    public void onComplete(@NonNull Task <RemoteInsertManyResult> task) {
        if (task.isSuccessful()) {
            Log.d("app",
                String.format("successfully inserted %d items with ids: %s",
                    task.getResult().getInsertedIds().size(),
                    task.getResult().getInsertedIds().toString()));
        } else {
            Log.e("app", "failed to inserts document with: ", task.getException());
        }
    }
});
// Insert two documents into the items collection
let doc1: Document = [
    "name": "basketball",
    "category": "sports",
    "quantity": 20,
    "reviews": []
];

let doc2: Document = [
    "name": "football",
    "category": "sports",
    "quantity": 30,
    "reviews": []
];

itemsCollection?.insertMany([doc1, doc2]) { result in
    switch result {
    case .success(let result):
        print("Successfully inserted items with _ids: \(result.insertedIds))");
    case .failure(let error):
        print("Failed to insert items: \(error)");
    }
}