Navigation

Query MongoDB - React Native SDK

Note
Example Dataset

The examples on this page use a MongoDB collection that describes inventory in a chain of plant stores. For more information on the collection schema and document contents, see Example Data.

To access a linked cluster from your client application, pass the cluster name to User.mongoClient(). This returns a MongoDB service interface that you can use to access databases and collections in the cluster.

To find a single document, pass a query filter that matches the document to collection.findOne(). If you do not pass a query filter, findOne() matches the first document it finds in the collection.

The following snippet finds the document that describes "venus flytrap" plants in the collection of documents that describe plants for sale in a group of stores:

Running this snippet produces output resembling the following:

To find multiple documents, pass a query filter that matches the documents to collection.find(). If you do not pass a query filter, find() matches all documents in the collection.

The following snippet finds all documents that describe perennial plants in the collection of documents that describe plants for sale in a group of stores:

Running this snippet produces output resembling the following:

To count documents, pass a query filter that matches the documents to collection.count(). If you do not pass a query filter, count() 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:

Running this snippet produces output resembling the following:

To insert a single document, pass it to 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:

Running this snippet produces output resembling the following:

To insert multiple documents at the same time, pass them as an array to collection.insertMany().

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

Running this snippet produces output resembling the following:

To update a single document, pass a query filter that matches the document and an update document to 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":

Running this snippet produces output resembling the following:

To update multiple documents simultaneously, pass a query filter that matches the documents and an update description to 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":

Running this snippet produces output resembling the following:

To upsert a document, set the upsert option to true in your update operation. If the operation's query filter does not match any document in the collection, an upsert automatically inserts a single new document into the collection that matches the provided query document with the update applied to it.

The following snippet updates a document in a collection of documents that describe plants for sale in a group of stores with an upsert operation. The query doesn't match any existing documents, so MongoDB automatically creates a new one.

Running this snippet produces output resembling the following:

To delete a single document from a collection, pass a query filter that matches the document to collection.deleteOne(). If you do not pass a query filter or if the query filter matches multiple documents, then the operation deletes the first document it finds.

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:

Running this snippet produces output resembling the following:

To delete multiple document from a collection, pass a query filter that matches the documents to collection.deleteMany(). If you do not pass a query filter, deleteMany() deletes all documents in the collection.

The following snippet deletes all documents for plants that are in "Store 51" in a collection of documents that describe plants for sale in a group of stores:

Running this snippet produces output resembling the following:

You can call collection.watch() to subscribe to real-time change notifications that MongoDB emits whenever a document in the collection is added, modified, or deleted. Each notification specifies a document that changed, how it changed, and the full document after the operation that caused the event.

Note

collection.watch() returns an async generator that allows you to asynchronously pull change events for operations as they occur.

To watch for all changes in a collection, call collection.watch() with no arguments:

To watch for specific changes in a collection, pass a query filter that matches change event fields to collection.watch():

Aggregation operations run all documents in a collection through a series of stages called an aggregation pipeline. Aggregation allows you to filter and transform documents, collect summary data about groups of related documents, and other complex data operations.

To execute an aggregation pipeline, pass an array of aggregation stages to collection.aggregate(). Aggregation operations return the result set of the last stage in the pipeline.

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

Running this snippet produces output resembling the following:

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"
},
}
}

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 }
}
}

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 ] }
}
}

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 ] }
}
}

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 }
}

The examples on this page use the following MongoDB collection that describes various plants for sale in a chain of plant stores:

{ _id: ObjectId("5f87976b7b800b285345a8b4"), name: "venus flytrap", sunlight: "full", color: "white", type: "perennial", _partition: "Store 42" },
{ _id: ObjectId("5f87976b7b800b285345a8b5"), name: "sweet basil", sunlight: "partial", color: "green", type: "annual", _partition: "Store 42" },
{ _id: ObjectId("5f87976b7b800b285345a8b6"), name: "thai basil", sunlight: "partial", color: "green", type: "perennial", _partition: "Store 42" },
{ _id: ObjectId("5f87976b7b800b285345a8b7"), name: "helianthus", sunlight: "full", color: "yellow", type: "annual", _partition: "Store 42" },
{ _id: ObjectId("5f87976b7b800b285345a8b8"), name: "petunia", sunlight: "full", color: "purple", type: "annual", _partition: "Store 47" }

Documents in the plants collection use the following schema:

Give Feedback

On this page