• Tutorials >
  • Integrate the MongoDB Service with your Android Application

Integrate the MongoDB Service with your Android Application

On this page

The MongoDB Stitch Android SDK provides methods for integrating the MongoDB service configured in your MongoDB Stitch application into your Android application.

This tutorial integrates the Stitch Android SDK into an application that stores data on restaurants and allows users to leave comments. The application uses the Stitch SDK to perform anonymous user authentication and access a MongoDB database via the MongoDB service.

You can apply the general strategies and structure used in this tutorial as a baseline for utilizing the Stitch Android SDK and MongoDB service in your own application.


To complete this tutorial you need:

  • A MongoDB Atlas cluster using MongoDB version 3.4+. The tutorial uses an Atlas Free Tier cluster.
  • An Android development environment such as Android Studio. The minimum supported Android API level for MongoDB Stitch is 19 (Android 4.4. KitKat).

For complete documentation on the MongoDB Stitch Android SDK, see the Stitch Android SDK API.


A. Create a MongoDB Stitch App

Estimated Time to Complete: ~8 minutes


Log into Atlas.

To use MongoDB Stitch, you must be logged into MongoDB Atlas. If you do not have an Atlas account, follow the instructions in the Atlas documentation to create an account.


Create an Atlas cluster.

If you do not already have an Atlas cluster for use with MongoDB Stitch, create a cluster.


You must deploy the Atlas cluster with MongoDB version 3.4 or greater.

Atlas provides a Free Tier M0 replica set as well as paid M10+ clusters. Free Tier deployments have restrictions as compared to paid M10+ deployments but will work for the purposes of this tutorial. For complete documentation on these restrictions, see Atlas M0 (Free Tier), M2, and M5 Limitations.


Add a MongoDB Stitch application.

  1. In Atlas, click Stitch Apps in the left-hand navigation.
  2. Click the Create New Application. The name can only contain ASCII letters, numbers, underscores, and hyphens.
  3. Select your Atlas cluster for your MongoDB service.
  4. Click Create.

Upon creation of your app, you will be redirected to the MongoDB Stitch console. Your app is created with a MongoDB service named mongodb-atlas.

B. Define Namespace and Rules

Estimated Time to Complete: ~10 minutes


Create a new namespace.

  1. Click the NEW button to open the namespace configuration dialog.
  2. For Database, enter guidebook.
  3. For Collection, enter restaurants.
  4. Click Create.

Review the rules for guidebook.restaurants collection.

Click on the newly created guidebook.restaurants namespace to view the read rule, write rule, the validation rule, and the filter rule.

MongoDB Authorization

Stitch rules do not override the read and write access (i.e. authorization) that may have been set up separately in MongoDB. That is, Stitch rules determine whether the fields are readable or writable; not whether the client has authorization to read or write to a particular database or collection.

Similarly, Stitch validation rules do not override document validation rules set up separately in MongoDB.


Review the read rule for the top-level document in guidebook.restaurants.

Modify the top-level document read rule to the following and click SAVE:

{ }

The new rule specifies that all the fields in the documents are always readable.

For more information on MongoDB read rules, see MongoDB Service Read Rule.


Review the write rule for the top-level document in guidebook.restaurants.

Remove all text from the write rule on the top-level document and leave it blank.

This allows you to modify the write rules at the field level.


Add a new write rule for the comments field.

  1. Click the + ADD… button.

  2. Enter comments in the Field Name box.

  3. Click ADD.

  4. Click on the right-side dropdown menu which defaults to Any and select Array.

  5. Click on the <array-elements> line.

  6. In the WRITE text field enter the following rule:

      "user_id": ""

    This rule directs MongoDB Stitch to reject any write operation where the value passed to the user_id field does not match the of the authenticated client.

  7. Click the green SAVE button.

For more information on MongoDB write rules, see MongoDB Service Write Rule.


Delete the owner_id field.

For this collection, the owner_id field does not exist.

Mouse over the owner_id field and click the x on the right-hand side.


Allow all other fields for guidebook.restaurants.

By default, Allow All Other Fields flag is enabled so that any unlisted fields are readable/writeable as long as the document meets the read/write rules. Alternatively, you can explicitly define all the fields for this collection and disable Allow All Other Fields to control the shape of the documents.


Review filters for guidebook.restaurants.

  1. Click on Filters.
  2. Click DELETE to delete the default filter.
  3. Click Save.

For more information on filters, see MongoDB Service Filters.

C. Set Up Anonymous Auth

Estimated Time to Complete: ~2 minutes

This tutorial uses anonymous user authentication for the app. While MongoDB Stitch supports OAuth authentication with Google and Facebook accounts, those integrations are outside the scope of this tutorial.


Click Authentication in the left side navigation in the MongoDB Stitch console.

The Authentication page displays the Authentication Providers information.


Enable Anonymous Authentication.

  1. For Allow users to log in anonymously, click the Edit button.
  2. Switch Allow users to log in anonymously to enabled.
  3. Close the dialog.

For complete documentation on configuring authentication in MongoDB Stitch, see Authentication.

D. Populate the restaurants Collection

Estimated Time to Complete: ~10 minutes

The app expects documents in the guidebook.restaurants collection to have the following schema:

   "name" : <string>,
   "cuisine" : <string>,
   "location" : <string>,
   "comments" : [
      { "user_id" : <string>, "comment" : <string> },

The app allows users to add comments to existing restaurant records, but it has no facility for adding new restaurant records, so you need to populate your database before testing the app.

Copy the following documents to a file named restaurants.json file and use mongoimport to load them into the guidebook.restaurants collection.

   "name" : "Bistro Maxime",
   "cuisine" : "French",
   "location" : "Boston, MA",
   "comments" : [ { "user_id" : "josephine", "comment" : "Avoid the goose liver paté." } ]

   "name" : "Tacqueria El Grullense",
   "cuisine" : "Mexican",
   "location" : "Sant Cruz, CA",
   "comments" : [ { "user_id" : "foodie123", "comment" : "Amazing food!" } ]

   "name" : "Don Giovanni",
   "cuisine" : "Italian",
   "location" : "Chicago, IL",
   "comments" : [ { "user_id" : "leporello", "comment" : "Molto bene" } ]

See Import Data into Cluster for more information about importing data with Atlas.

E. Test the Data Source

Optional. Estimated Time to Complete: ~8 minutes

You can make sure your MongoDB service is configured correctly by trying a test query in the Stitch console’s Debug Console.


Create an app user.

To use the Debug Console your app must have at least one user to perform operations. To create a user:

  1. Click Authentication in the left side navigation.
  2. Click the EDIT button in the row labeled API Keys.
  3. Click the CREATE API KEY button.
  4. Give the key a name.
  5. Click SAVE and close the window.

Run a query in the Debug Console.

  1. Click the Debug Console link in the left side navigation.

  2. Click the SELECT USER button and select a user.

  3. Click Done.

  4. Mouse over the pipeline panel and click EDIT.

  5. Select your MongoDB service from the SERVICE dropdown menu and FIND from the ACTION dropdown menu.

  6. Enter the following query in the JSON panel:

      "database": "guidebook",
      "collection": "restaurants"
  7. Click DONE.

  8. Click EXECUTE to run the query.

If your connection is correctly set up, the complete contents of the restaurants collection appears in the Result panel.

If no results appear, check your MongoDB service rules. Make sure the rules are consistent with your database schema.

F. Download the MongoRestaurant Application Source

Estimated Time to Complete: ~2 minutes

Download from the MongoDB Stitch GitHub example repository and unzip. The source code for the MongoRestaurant application can be found in the MongoRestaurant-android directory.

G. Set Up the App

Estimated Time to Complete: ~10 minutes


Open the MongoRestaurant source code in Android Studio.

Launch Android Studio. Open the MongoRestaurant source code folder as a new project.


Edit the file.

Replace the following placeholders in the file:

  • STITCH-APP-ID with your Stitch App ID
  • MONGODB-SERVICE-NAME with mongodb-atlas

You can find your App ID in the Clients view in the Stitch console.


Review code to connect to MongoDB Stitch.

The Stitch SDK provides classes for interfacing with the application and the MongoDB service: StitchClient and MongoClient.

  • StitchClient(Context context, String clientAppID)

    This object handles interactions between the application and Stitch, including authentication and pipelines. Takes as parameters the current context and a string representing the app ID as parameters.

  • MongoClient(StitchClient client, String service)

    This object handles interactions between the application and the MongoDB service, such as CRUD operations or aggregation pipelines. Takes a StitchClient object and a string representing the MongoDB service name as parameters.

The following snippet uses the onCreate() method to instantiate each class.

public class MainActivity extends AppCompatActivity {

    // Remember to replace the APP_ID with your Stitch Application ID

    private static final String APP_ID = "STITCH-APP-ID"; //The Stitch Application ID
    private static final String TAG = "STITCH-SDK";
    private static final String MONGODB_SERVICE_NAME = "mongodb-atlas";

    private StitchClient _client;
    private MongoClient _mongoClient;

    private String currentRestaurantName;

    protected void onCreate(Bundle savedInstanceState) {

        _client = new StitchClient(this.getBaseContext(), APP_ID);
        _mongoClient = new MongoClient(_client, MONGODB_SERVICE_NAME);

        currentRestaurantName = "";

Review code to authenticate application users.

The Stitch SDK provides the following objects and related methods for retrieving the authentication providers configured for the application, as well as performing authentication using a given authentication provider.

  • StitchClient.getAuthProviders()

    Returns a Task<AvailableAuthProviders> object. The AvailableAuthProviders class provides methods for checking which authentication providers are configured for the application.

  • AvailableAuthProviders.hasAnonymous()

    Returns a boolean. If true, the application has anonymous authentication configured.

  • StitchClient.logInWithProvider(AuthProvider authProvider)

    Returns a Task<Auth> object. Takes an AuthProvider object, such as the AnonymousAuthProvider() class.

Use the StitchClient.getAuthProviders() method to retrieve the configured authentication providers for the specified application. Use the StitchClient.logInWithProvider() to log in with the specified authentication provider.

The following snippet retrieves the authentication providers for the application and, if anonymous authentication is configured, performs anonymous authentication.

private void doAnonymousAuthentication() {

    _client.getAuthProviders().addOnCompleteListener(new OnCompleteListener<AvailableAuthProviders>() {
        public void onComplete(@NonNull final Task<AvailableAuthProviders> task) {
            if (!task.isSuccessful()){
                Log.e(TAG, "Could not retrieve authentication providers");
            } else {
                Log.i(TAG, "Retrieved authentication providers");

                if (task.getResult().hasAnonymous()){
                    _client.logInWithProvider(new AnonymousAuthProvider()).continueWith(new Continuation<Auth, Object>() {
                        public Object then(@NonNull final Task<Auth> task) throws Exception {
                            if (task.isSuccessful()) {
                                Log.i(TAG,"User Authenticated as " + _client.getAuth().getUserId());
                            } else {
                                Log.e(TAG, "Error logging in anonymously", task.getException());
                            return null;

For more information, see Stitch Authentication.


Review code to access the MongoDB service and collections.

The Stitch SDK provides the following objects and related methods for interacting with the Atlas cluster linked through the MongoDB service:

  • MongoClient.getDatabase(String name)

    Returns a MongoDB Database object. Takes a String representing the name of the MongoDB database.

  • Database.getCollection(String name)

    Returns a MongoDB Collection object. Takes a String representing the name of the collection in relation to the Database object.

You can perform operations on either the database object or the collection object, depending on your objectives. For example, the following code snippet does the following:

  • Returns a database object that references the guidebook database.
  • Returns a collection object that references the restaurants collection.
  • Uses the updateOne() method to append a user comment to an array.
_mongoClient.getDatabase("guidebook").getCollection("restaurants").updateOne(query,update).continueWith(new Continuation<Void, Object>() {
    public Object then(@NonNull final Task<Void> task) {
        if (task.isSuccessful()) {
        } else {
            Log.e(TAG,"Error writing comment");
        return null;

The following code snippet uses the find() method to search the guidebook.restaurants collection, retrieving the first document whose name field matches the user input.

_mongoClient.getDatabase("guidebook").getCollection("restaurants").find(query).continueWith(new Continuation<List<Document>, Object>() {
    public Object then(@NonNull final Task<List<Document>> task) {
        if (!task.isSuccessful()){
            Log.e(TAG, "Error refreshing comments");
        } else {

            final Document result = task.getResult().get(0);
            final List<Document> comments = (List<Document>) result.get("comments");

            if (comments.size() > 0 ){

H. Run the App

If your app is compiling correctly in Android Studio, you can run it with either a USB-connected physical device or a virtual device. Make sure Enable ADB Integration is checked in the Tools > Android menu.

For more information about running Android apps, see the Android Studio documentation.