Navigation

Insert Documents

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": { "bsonType": "objectId" },
    name: { "bsonType": "string" },
    quantity: { "bsonType": "int" },
    reviews: {
      "bsonType": "array",
      "items": {
        "username": { "bsonType": "string" },
        "comment": { "bsonType": "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 an iOS project, you must first do the following:

1

Set Up Your Project

Follow the steps in the Install Realm for iOS, macOS, tvOS, and watchOS guide.

2

Import Realm Dependencies

In scope (e.g. UIViewController)
import RealmCore
import RealmCoreRemoteMongoDBService
import RealmRemoteMongoDBService
3

Initialize the MongoDB Realm iOS SDK

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

Instantiate a MongoDB Collection Handle

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

// Set the realm variables declared above in viewDidLoad()
mongoClient = realmClient.serviceClient(
    fromFactory: remoteMongoClientFactory,
    withName: "mongodb-atlas"
)
itemsCollection = mongoClient?.db("store").collection("items")
purchasesCollection = mongoClient?.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 Install Realm for Android guide.

2

Import Realm Dependencies

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

// Base Realm Packages
import com.mongodb.realm.android.core.Realm;
import com.mongodb.realm.android.core.RealmAppClient;
// Realm Authentication Packages
import com.mongodb.realm.android.core.auth.RealmUser;
import com.mongodb.realm.core.auth.providers.anonymous.AnonymousCredential;

// MongoDB Service Packages
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
// Utility Packages
import com.mongodb.realm.core.internal.common.BsonUtils;

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

// Realm Sync Packages
import com.mongodb.realm.core.services.mongodb.remote.sync.ChangeEventListener;
import com.mongodb.realm.core.services.mongodb.remote.sync.DefaultSyncConflictResolvers;
import com.mongodb.realm.core.services.mongodb.remote.sync.ErrorListener;
import com.mongodb.realm.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.realm.android.services.mongodb.local.LocalMongoDbService;
3

Instantiate a MongoDB Collection Handle

Top of Activity File
private RealmAppClient realmClient;
private RemoteMongoClient mongoClient;
private RemoteMongoCollection itemsCollection;
In Activity.onCreate()
realmClient = Realm.getDefaultAppClient();
mongoClient = realmClient.getServiceClient(RemoteMongoClient.factory, "mongodb-atlas");

itemsCollection = mongoClient.getDatabase("store").getCollection("items");
purchasesCollection = mongoClient.getDatabase("store").getCollection("purchases");

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

1

Import Realm Dependencies

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

– or –

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

Instantiate a MongoDB Remote Collection Handle

const realmApp = Realm.initializeDefaultAppClient("<Your App ID>");
const mongodb = realmApp.getServiceClient(RemoteMongoClient.factory, "mongodb-atlas");

const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.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}`))
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)");
    }
}
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());
        }
    }
});
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}`))

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}`))
// 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)");
    }
}
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());
        }
    }
});
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}`))