Navigation

MongoDB Atlas Overview

Introduction

The MongoDB Service is a secure, cross-platform interface for working with data stored in a Atlas cluster. With the MongoDB Service, you can safely query data stored in MongoDB from anywhere in your application: client or server.

The service ensures that data is secure by filtering all requests according to sophisticated, role-based data access rules that you define for each collection. When Stitch receives a read or write request, it dynamically evaluates the rules for the specified collection and only exposes data that the Stitch user who issued the request has permission to interact with. If you haven’t configured any rules for a collection, Stitch automatically prevents all read and write operations on it.

Set Up the MongoDB Service

Configure Collection Rules

Before you can access Atlas data with Stitch, you must configure rules for each collection that you want to access.

To learn more, see Add MongoDB to Your Stitch App.

Query MongoDB Anywhere

Data access rules effectively give each user a unique, permissioned view of the data in a collection. This makes it safe to query MongoDB wherever you need to, including directly from your client application.

Once you’ve configured rules for a collection you can query MongoDB from a Stitch Function or a Client SDK.

Query MongoDB from a Stitch Function

You can query MongoDB on the server by using MongoDB Actions in a function.

exports = async function() {
  // Get the service interface from context
  const mongodb = context.services.get("mongodb-atlas");
  const orders = mongodb.db("store").collection("orders");

  // Read data from a collection
  const largeOrders = await orders.find({ total: { $gte: 200 } }).toArray();

  // Insert a document
  const insertResult = await orders.insertOne({ total: 240 });

  // Update a document
  const updateResult = await orders.updateOne(
    { "_id": insertResult.insertedId },
    { "$set": { "total": 220 } }
  )
}

Query MongoDB from a Client SDK

You can query MongoDB directly from a client application by using the appropriate Client SDK for your platform:

Note

For more information, see the JavaScript Browser SDK docs.

const { Stitch, RemoteMongoClient } = stitch;
const stitchClient = Stitch.getDefaultAppClient("myapp-abcde");

async function mongodbExample() {
  // Get the MongoDB Service client from the App Client
  const mongodb = stitchClient.getServiceClient(
    RemoteMongoClient.factory,
    "mongodb-atlas"
  );
  const orders = mongodb.db("store").collection("orders");

  // Read data from a collection
  const largeOrders = await orders.find(
    { total: { $gte: 200 } },
    { limit: 200 }
  )
   .asArray();

  // Insert a document
  const insertResult = await orders.insertOne({ total: 240 });

  // Update a document
  const updateResult = await orders.updateOne(
    { "_id": insertResult.insertedId },
    { "$set": { "total": 220 } }
  )
}

Note

For more information, see the Android SDK docs.

// Get the MongoDB Service client from the App Client
_client = Stitch.getDefaultAppClient();
_mongoClient = _client.getServiceClient(RemoteMongoClient.Factory, "mongodb-atlas");
RemoteMongoCollection orders = _mongoClient.db("store").collection("orders");

// Read data from a collection
final Document query = Document.parse("{ 'total': { '$gte': 200 } }")
RemoteFindIterable cursor = orders.find(query).limit(200);
final ArrayList<Document> findResults = new ArrayList<>();
cursor.into(findResults).addOnCompleteListener(new onCompleteListener() {
  @Override
  public void onComplete(@NonNull Task task) {
    if (task.isSuccessful()) { /* do something... */ }
    else { /* handle the exception... */ }
  }
})

// Insert a document
final Document insertDoc = new Document("total", 240);
orders.insertOne(insertDoc).addOnCompleteListener(new onCompleteListener() {
  @Override
  public void onComplete(@NonNull Task task) {
    if (task.isSuccessful()) { /* do something... */ }
    else { /* handle the exception... */ }
  }
})

// Update a document
final Document updateFilter = new Document("_id", 12);
final Document updateOperation = new Document("$set", new Document("total", 220));
const updateResult = orders.updateOne(updateFilter, updateOperation)

Note

For more information, see the iOS SDK docs.

private var stitchClient: StitchAppClient!
private var mongoClient: RemoteMongoClient?

// Get the MongoDB Service client from the App Client
stitchClient = Stitch.defaultAppClient
mongoClient = stitchClient.serviceClient(
  fromFactory: remoteMongoDBServiceClientFactory,
  withName: "mongodb-atlas"
)

// Read data from a collection
let query: Document = ["total": ["$gte": 200]]
collection.find(query, options: RemoteFindOptions.init(limit: 200)).asArray { result in
  var documents: [Document]
  switch result {
    case .success(let d):
      documents = d
    case .failure(let error):
      return error
  }
  // Do something with the returned documents
}

// Insert a document
var insertDoc: Document = ["total": 240]
collection.insertOne(insertDoc) { result in
  var document: Document
  switch result {
    case .success(let d):
      document = d
    case .failure(let error):
      return error
  }
  // Do something with the returned document
}

// Update a document
let updateFilter: Document = ["_id": ObjectId()]
let updateOperation = ["$set": ["total": 200]]
collection.updateOne(filter: updateFilter, update: updateOperation) { result in
  switch result {
    case .success(let updateResult):
      // Do something with the RemoteUpdateResult object
    case .failure(let error):
      return
  }
}

Considerations

System-Generated Cluster Users

Stitch automatically creates a MongoDB user for each app linked to a cluster. These users are for internal use only and cannot be edited or manually deleted. If you delete a Stitch app, the associated user will also be deleted.

Users generated by Stitch have names of the form: mongodb-stitch-<your app id>

Accessing Application Data with Another Tool

Stitch connects to standard MongoDB Atlas clusters, which means that you can connect directly to a linked cluster using another tool such as the mongo shell or MongoDB Compass. There are no special considerations when reading data from a linked cluster with another tool.

While running update operations, Stitch temporarily adds a reserved field, _id_stitch_transaction, to documents. Once a document is successfully updated, Stitch removes this field. If you want to use another tool to modify data in a collection, ensure that you $unset this field prior to making changes.

For example, if you are using the mongo shell to update documents in the products collection, your command might resemble the following code:

db.products.update(
   { sku: "unknown" },
   { $unset: { _id_stitch_transaction: "" } }
)