Navigation

MongoDB Data Access

The following actions enable access to a linked MongoDB Atlas cluster from a React Native application using the Realm Node SDK.

Note

Each operation described on this page uses a query filter to match certain documents in the collection upon which the operation executes. When a filter matches multiple documents in a collection, they are returned in an indeterminate order unless you specify a sorting parameter. This means that if you do not specify a sort for the findOne(), updateOne(), or deleteOne() functions, your operation could match any document that matches the query filter. For more information on sorting, see cursor.sort().

Set Up Your Project

1

Set Up Your Project

Follow the steps in the Install Realm for React Native guide.

2
3

Import Realm Dependencies

At the top of your source files where you want to use MongoDB Realm, add the following line to import the SDK.

import Realm from "realm";
4

Instantiate a MongoDB Collection Handle

const appId = "<your App ID>"; // Set Realm app ID here.
const appConfig = {
  id: appId,
  timeout: 10000, // timeout in milliseconds
};

async function run() {
  let user;
  try {
    const app = new Realm.App(appConfig);

    // an authenticated user is required to access a MongoDB instance
    user = await app.logIn(Realm.Credentials.anonymous());

    const mongoClient = user.remoteMongoClient("<atlas service name>");
    const mongoCollection = mongoClient
      .db("<database name>")
      .collection("<collection name");

      // the rest of your code ...


   } finally {
     user.logOut();
   }
 }
 run().catch(console.dir);

Example Data

The following examples operate on a MongoDB collection that describes inventory in a chain of plant stores. Consider the following collection of documents describing various plants for sale in store:

[{"name": "venus flytrap", "sunlight": "full", "color": "white", "type": "perennial", "_partition": "Store 42"},
 {"name": "sweet basil", "sunlight": "partial", "color": "green", "type": "annual", "_partition": "Store 42"},
 {"name": "thai basil", "sunlight": "partial", "color": "green", "type": "perennial", "_partition": "Store 42"},
 {"name": "helianthus", "sunlight": "full", "color": "yellow", "type": "annual", "_partition": "Store 42"},
 {"name": "petunia", "sunlight": "full", "color": "purple", "type": "annual", "_partition": "Store 47"}]

Create Documents

These code snippets demonstrate how to insert one or more documents into a MongoDB collection from a React Native application. Insert operations take a document or documents to add to MongoDB as an argument and return a Promise that resolves to an object that contains the results of the execution of the operation.

Insert a Single Document

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

The following snippet inserts a single document describing a “lily of the valley” plant into a collection of documents that describe plants for sale in a group of stores:

const plant = {
  name: "lily of the valley",
  sunlight: "full",
  color: "white",
  type: "perennial",
  _partition: "Store 47",
};
const insertOneResult = await mongoCollection.insertOne(plant);
console.log(insertOneResult);

Running this snippet produces output resembling the following:

{ insertedId: 5f1f43972b0979dc01cd786c }

Insert Multiple Documents

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

The following snippet inserts three documents describing plants into a collection of documents that describe plants for sale in a group of stores:

const plants = [
  {
    name: "rhubarb",
    sunlight: "full",
    color: "red",
    type: "perennial",
    _partition: "Store 47",
  },
  {
    name: "wisteria lilac",
    sunlight: "partial",
    color: "purple",
    type: "perennial",
    _partition: "Store 42",
  },
  {
    name: "daffodil",
    sunlight: "full",
    color: "yellow",
    type: "perennial",
    _partition: "Store 42",
  },
];
const insertManyResult = await mongoCollection.insertMany(plants);
console.log(insertManyResult);

Running this snippet produces output resembling the following:

{
   insertedIds: [
     5f1f4500e0ef86239b6d7ae6,
     5f1f4500e0ef86239b6d7ae7,
     5f1f4500e0ef86239b6d7ae8
   ]
}

Read Documents

These code snippets demonstrate how to read data stored in a MongoDB collection from a mobile application. Read operations use query filters to specify which documents to return from the database. Read operations return a Promise that resolves to either a single matched document (in the case of findOne()), a numeric value (in the case of count()) or an array of matched documents (in the case of find()).

Find a Single Document

You can find a single document using collection.insertOne().

The following snippet finds a single document from the a collection of documents that describe plants for sale in a group of stores where the plant document’s type field contains the string value “perennial”:

const queryFilter = { type: "perennial" };
const perennialResultDocument = await mongoCollection.findOne(queryFilter);
console.log(perennialResultDocument);

Running this snippet produces output resembling the following:

{
  _id: 5f1f4266e0ef86239b6c416c,
  name: 'venus flytrap',
  sunlight: 'full',
  color: 'white',
  type: 'perennial',
  _partition: 'Store 42'
}

Find Multiple Documents

You can find multiple documents using collection.insertOne().

The following snippet finds all documents in a collection of documents that describe plants for sale in a group of stores that contain a field named _partition with a value of “Store 42”:

const findManyQueryFilter = { _partition: "Store 42" };
const allPlantsFromStore42Result = await mongoCollection.find(findManyQueryFilter);
console.log(allPlantsFromStore42Result);

Running this snippet produces output resembling the following:

[ { _id: 5f1f4266e0ef86239b6c416c, name: 'venus flytrap', sunlight: 'full', color: 'white', type: 'perennial', _partition: 'Store 42' }, { _id: 5f1f4266e0ef86239b6c416d, name: 'sweet basil', sunlight: 'partial', color: 'green', type: 'annual', _partition: 'Store 42' }, { _id: 5f1f4266e0ef86239b6c416e, name: 'thai basil', sunlight: 'partial', color: 'green', type: 'perennial', _partition: 'Store 42' }, { _id: 5f1f4266e0ef86239b6c416f, name: 'helianthus', sunlight: 'full', color: 'yellow', type: 'annual', _partition: 'Store 42' }, { _id: 5f1f4500e0ef86239b6d7ae7, name: 'wisteria lilac', sunlight: 'partial', color: 'purple', type: 'perennial', _partition: 'Store 42' }, { _id: 5f1f4500e0ef86239b6d7ae8, name: 'daffodil', sunlight: 'full', color: 'yellow', type: 'perennial', _partition: 'Store 42' } ]

Count Documents in the Collection

You can count documents in a collection using collection.count(). You can specify an optional query filter to determine which documents to count. If you don’t specify a query, the action counts all documents in the collection.

The following snippet counts the number of documents in a collection of documents that describe plants for sale in a group of stores:

const countResult = await mongoCollection.count();
console.log(`successfully counted, number of documents in the collection: ${countResult}`);

Running this snippet produces output resembling the following:

successfully counted, number of documents in the collection: 5

Update Documents

These code snippets demonstrate how to update data stored in a MongoDB collection from a mobile application. Update operations use query filters to specify which documents to update and update operators to describe how to mutate documents that match the query. Update operations return a Promise that resolves to an object that contains the results of the execution of the operation.

Update a Single Document

You can update a single document using collection.updateOne().

The following snippet updates a single document in a collection of documents that describe plants for sale in a group of stores. This operation queries for a document where the name field contains the value “petunia” and changes the value of the first matched document’s sunlight field to “partial”:

const queryFilter = { name: "petunia" };
const updateDocument = { sunlight: "partial" };
const updateResult = await mongoCollection.updateOne(queryFilter, updateDocument);
console.log(updateResult);

Running this snippet produces output resembling the following:

{ matchedCount: 1, modifiedCount: 1 }

Update Multiple Documents

You can update a single document using collection.updateMany().

The following snippet updates multiple documents in a collection of documents that describe plants for sale in a group of stores. This operation queries for documents where the _partition field contains the value “Store 47” and changes the value of the _partition field of each matching document to “Store 51”:

const queryFilter = { _partition: "Store 47" };
const updateDocument = { _partition: "Store 51" };
const updateResult = await mongoCollection.updateMany(queryFilter, updateDocument);
console.log(updateResult);

Running this snippet produces output resembling the following:

{ matchedCount: 2, modifiedCount: 2 }

Upsert Documents

If an update operation does not match any document in the collection, you can automatically insert a single new document into the collection that matches the update query by setting the upsert option to true.

The following snippet updates a document in a collection of documents that describe plants for sale in a group of stores or inserts a new document if no document matches the query filter. This operation queries for documents where:

  • the sunlight field has a value of “full”
  • the type field has a value of “perennial”
  • the color field has a value of “green”
  • the _partition field has a value of “Store 47”

Because this snippet sets the upsert option to true, if no document matches the query, MongoDB creates a new document that includes both the query filter and specified updates:

const queryFilter = {
  sunlight: "full",
  type: "perennial",
  color: "green",
  _partition: "Store 47",
};
const updateDocument = {
  name: "sweet basil",
};
const updateOptions = {
  upsert: true,
};

const upsertResult = await mongoCollection.updateOne(
  queryFilter,
  updateDocument,
  updateOptions
);
console.log(upsertResult);

Running this snippet produces output resembling the following:

{ matchedCount: 0, modifiedCount: 0, upsertedId: 5f1f63055512f2cb67f460a3 }

Delete Documents

These code snippets demonstrate how to delete documents that are stored in a MongoDB collection from a mobile application. Delete operations use a query filter to specify which documents to delete and return a Promise that resolves to an object that contains the results of the execution of the operation.

Delete a Single Document

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

The following snippet deletes one document in a collection of documents that describe plants for sale in a group of stores. This operation queries for a document where the color field has a value of “green” and deletes the first document that matches the query:

const queryFilter = { color: "green" };
const deleteResult = await mongoCollection.deleteOne(queryFilter);
console.log(deleteResult);

Running this snippet produces output resembling the following:

{ deletedCount: 1 }

Delete Multiple Documents

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

The following snippet deletes all documents in a collection of documents that describe plants for sale in a group of stores that match the query filter that matches documents containing both a sunlight field value of “full” and a type field value of “annual”.

const queryFilter = {
  sunlight: "full",
  type: "annual",
};
const deleteManyResult = await mongoCollection.deleteMany(queryFilter);
console.log(deleteManyResult);

Running this snippet produces output resembling the following:

{ deletedCount: 2 }

Aggregate Documents

These code snippets demonstrate how to configure and run aggregation operations on a collection. Aggregation operations run all documents in a collection through a series of data aggregation stages called an aggregation pipeline that allow you to filter and shape documents as well as collect summary data about groups of related documents.

Aggregation operations accept a list of aggregation stages as input, and return a Promise that resolves to a collection of documents processed by the pipeline.

Aggregate Documents in a Collection

You can execute an aggregation pipeline using collection.aggregate().

The following snippet groups all documents in the plants collection by their type value and aggregates a count of the number of each type:

const aggregationResult = await mongoCollection.aggregate([
  { $group: { _id: "$type", total: { $sum: 1 } } },
]);
console.log(aggregationResult);

Running this snippet produces output resembling the following:

[ { _id: 'perennial', total: 2 }, { _id: 'annual', total: 1 } ]

Aggregation Stages

Filter Documents

You can use the $match stage to filter documents according to a standard query filter.

{
  "$match": {
    "<Field Name>": <Query Expression>,
    ...
  }
}

Example

The following $match stage filters documents to include only those where the type field has a value equal to “perennial”:

{
  "$match": {
    "type": {
      "$eq": "perennial"
    },
  }
}

Group Documents

You can use the $group stage to aggregate summary data for one or more documents. MongoDB groups documents based on the expression defined in the _id field of the $group stage. You can reference a specific document field by prefixing the field name with a $.

{
  "$group": {
    "_id": <Group By Expression>,
    "<Field Name>": <Aggregation Expression>,
    ...
  }
}

Example

The following $group stage arranges documents by the value of their _partition field and calculates the number of plant documents that each unique _partition value appears in.

{
  "$group": {
    "_id": "$_partition",
    "numItems": { "$sum": 1 }
  }
}

Project Document Fields

You can use the $project stage to include or omit specific fields from documents or to calculate new fields using aggregation operators. Projections work in two ways:

  • Explicitly include fields with a value of 1. This has the side-effect of implicitly excluding all unspecified fields.
  • Implicitly exclude fields with a value of 0. This has the side-effect of implicitly including all unspecified fields.

These two methods of projection are mutually exclusive: if you explicitly include fields, you cannot explicitly exclude fields, and vice versa.

Note

The _id field is a special case: it is always included in every query unless explicitly specified otherwise. For this reason, you can exclude the _id field with a 0 value while simultaneously including other fields, like _partition, with a 1. Only the special case of exclusion of the _id field allows both exclusion and inclusion in one $project stage.

{
  "$project": {
    "<Field Name>": <0 | 1 | Expression>,
    ...
  }
}

Example

The following $project stage omits the _id field, includes the name field, and creates a new field named storeNumber. The storeNumber is generated using two aggregation operators:

  1. $split separates the _partition value into two string segments surrounding the space character. For example, the value “Store 42” split in this way returns an array with two elements: “Store” and “42”.
  2. $arrayElemAt selects a specific element from an array based on the second argument. In this case, the value 1 selects the second element from the array generated by the $split operator since arrays index from 0. For example, the value [“Store”, “42”] passed to this operation would return a value of “42”.
{
  "$project": {
    "_id": 0,
    "name": 1,
    "storeNumber": { "$arrayElemAt": [ { "$split": [ "$_partition", " " ] }, 1 ] }
  }
}

Add Fields to Documents

You can use the $addFields stage to add new fields with calculated values using aggregation operators.

Note

$addFields is similar to $project but does not allow you to include or omit fields.

Example

The following $addFields stage creates a new field named storeNumber where the value is the output of two aggregate operators that transform the value of the _partition field.

{
  "$addFields": {
    "storeNumber": { "$arrayElemAt": [ { "$split": [ "$_partition", " " ] }, 1 ] }
  }
}

Unwind Array Values

You can use the $unwind stage to transform a single document containing an array into multiple documents containing individual values from that array. When you unwind an array field, MongoDB copies each document once for each element of the array field but replaces the array value with the array element in each copy.

{
  $unwind: {
    path: <Array Field Path>,
    includeArrayIndex: <string>,
    preserveNullAndEmptyArrays: <boolean>
  }
}

Example

The following $unwind stage creates a new document for each element of the items array in each document. It also adds a field called itemIndex to each new document that specifies the element’s position index in the original array:

{
  "$unwind": {
    "path": "$items",
    "includeArrayIndex": "itemIndex"
   }
}

Consider the following document from the a collection of purchases:

{
  _id: 123,
  customerId: 24601,
  items: [
    { name: "Baseball", quantity: 5 },
    { name: "Baseball Mitt", quantity: 1 },
    { name: "Baseball Bat", quantity: 1 },
  ]
}

If we apply the example $unwind stage to this document, the stage outputs the following three documents:

{
  _id: 123,
  customerId: 24601,
  itemIndex: 0,
  items: { name: "Baseball", quantity: 5 }
}, {
  _id: 123,
  customerId: 24601,
  itemIndex: 1,
  items: { name: "Baseball Mitt", quantity: 1 }
}, {
  _id: 123,
  customerId: 24601,
  itemIndex: 2,
  items: { name: "Baseball Bat", quantity: 1 }
}