Navigation

Build a MongoDB Mobile (Beta) App

The Stitch Java SDK and Stitch Swift (iOS) SDK support developing apps that connect to both Atlas and MongoDB Mobile (Beta) instances. To get started, you can download a Starter App, which has the foundation already built for you, or you can follow the steps below to create your own MongoDB Mobile (Beta)-enabled app.

Starter Apps

The Stitch Starter Apps are complete platform-specific projects that contain the code you need to connect your mobile app to Stitch, Atlas, and MongoDB Mobile (Beta). Each is pre-configured to use an existing Stitch app and sample data in an Atlas cluster, so you can use the starter app immediately. When you are ready, you can modify the starter app code to point to your own Stitch app and data.

To get started, view the Readme.md file in the starter app’s subfolder for platform-specific instructions.

Creating a New MongoDB Mobile (Beta) App

Prerequisites

To build a Stitch app that uses MongoDB Mobile (Beta), you need:

  • Android Studio or another IDE. The steps below have been tested with the latest version of Android Studio.
  • Support for API Level 24 or higher.

We also recommend the following device capabilities:

  • An ARM32, ARM64, or x86_64 device that is running an armeabi-v7a, arm64-v8a, or x86_64 image of Android 7.0 (Nougat) or later.
  • Boot option: Cold boot
  • 1GB RAM
  • 4GB internal storage
  • 1GB SD Card (Studio-managed)

Note

MongoDB Mobile (Beta) does not support x86 devices. By default, Android Studio selects an x86 image for AVD deployments, so if you are deploying your Android app to an AVD, be sure to select an x86_64 image for the AVD. Otherwise, you will see an error message similar to the following:

com.mongodb.embedded.client.MongoClientEmbeddedException: Failed to load the mongodb library: ‘mongo_embedded_capi’. Native library (com/sun/jna/android-x86/libjnidispatch.so) not found in resource path (.)

To build a Stitch app that uses MongoDB Mobile (Beta), you need to have Xcode and cocoapods installed. If you do not have cocoapods installed, you can install it from a terminal window with the following commands:

$ sudo gem install cocoapods
$ pod init

Once these prerequisites are met, you are ready to start building your mobile app.

Getting Started

To set up a new project that will use MongoDB Mobile (Beta), follow these steps:

  1. Download and install the MongoDB Mobile (Beta) tarball:

    1. Download the tarball file for your specific platform:

    2. Extract the contents of the tarball, and then copy the contents of the lib subdirectory to the /src/main/jniLibs/platform directory, where platform is armeabi-v7a, arm64-v8a, or x86_64.

      When you are finished, your directory structure should look similar to this:

      MyAndroidApp
      └── app
           └── src
               └── main
                   └── jniLibs
                       └── x86_64 (or arm64-v8a or armeabi-v7a)
                           ├── cmake
                           ├── pkgconfig
                           ├── libaccumulator.so
                           ├── ...
      
  2. Open a project in Android Studio, or create a new project. Be sure to set the minimum API level for the project to 24.

  3. Add the following dependencies to the app’s Build.gradle file:

    implementation 'org.mongodb:stitch-android-sdk:4+'
    implementation 'org.mongodb:stitch-android-services-mongodb-local:4+'
    
  4. Sync the application to incorporate these changes.

    Note

    The initial sync will take a while as Gradle compiles MongoDB Mobile (Beta).

  1. Create new project in Xcode, or open an existing project. Set the Language to Swift.

  2. In a terminal window, complete the following steps:

    1. Navigate to the project directory created by Xcode.
    2. Run pod init in the directory, which will create the necessary pod files.
    3. Add the necessary the necessary pods to the Podfile:
    pod 'StitchCore', '<= 4.0.0'
    pod 'StitchLocalMongoDBService', '~> 4.0.0'
    
    1. Run pod install to install the pods.

    Note

    The initial installation will take a while as cocoapods installs MongoDB Mobile (Beta).

  3. Cocoapods has now created a new .xcworkspace for your project. You should quit the project in XCode and re-open it using this newly-created file. You project now has access to Stitch and MongoDB Mobile (Beta).

Initializing MongoDB Mobile

  1. Include the necessary packages:

    // Base Stitch Packages
    import com.mongodb.stitch.android.core.Stitch;
    import com.mongodb.stitch.android.core.StitchAppClient;
    
    // Packages needed to interact with MongoDB and Stitch
    import com.mongodb.client.MongoClient;
    import com.mongodb.client.MongoCollection;
    
    // Necessary component for working with MongoDB Mobile
    import com.mongodb.stitch.android.services.mongodb.local.LocalMongoDbService;
    
  2. Initialize the MongoDB Mobile database, and then create a MongoDB Mobile (Beta) client in the application:

    // Create the default Stitch Client
    final StitchAppClient client =
       Stitch.initializeDefaultAppClient("<APP ID>");
    
    // Create a Client for MongoDB Mobile (initializing MongoDB Mobile)
    final MongoClient mobileClient =
       client.getServiceClient(LocalMongoDbService.clientFactory);
    
  3. You can now access MongoDB Mobile (Beta) directly. For example, to point to a collection and insert a document, use the following code:

    // Point to the target collection and insert a document
    MongoCollection<Document> localCollection =
       mobileClient.getDatabase("my_db").getCollection("my_collection");
    
    localCollection.insertOne(document);
    
    // Find the first document
    Document doc = localCollection.find().first();
    
    //Find all documents that match the find criteria
    Document query = new Document();
    query.put("name", new BsonString("veirs"));
    
    FindIterable<Document> cursor = localCollection.find(query);
    ArrayList<Document> results =
       (ArrayList<Document>) cursor.into(new ArrayList<Document>());
    

In your project, add the following code to initialize the MongoDB Stitch client and MongoDB Mobile (Beta) connection:

// import the necessary modules to work with Stitch and MongoDB Mobile
import StitchCore
import StitchLocalMongoDBService
import StitchRemoteMongoDBService
import MongoSwiftMobile // required for BSON Documents

// Create the default Stitch Client
let client = try Stitch.initializeDefaultAppClient(
   withClientAppID: "<APP ID>"
)

// Create a Client for MongoDB Mobile (initializing MongoDB Mobile)
let localMongoClient =
   try client.serviceClient(fromFactory: mongoClientFactory)

Your code can now access MongoDB Mobile (Beta) directly. For example, to point to a collection and insert a document, use the following code:

let doc = Document() //add fields & values, etc.

// Point to the target collection and insert a document
let myLocalCollection = try localMongoClient.db("my_db")
   .collection("my_collection")
let result = try myLocalCollection.insertOne(doc)

Connecting with Stitch and Atlas

To use the SDKs to connect to MongoDB Stitch and pull data from an Atlas cluster to your MongoDB Mobile (Beta) instance, you can use the following code:

// Get a previously defined client
final StitchAppClient client = Stitch.getDefaultAppClient();

// Log-in using an Anonymous authentication provider from Stitch
// Then create a connection to a remote MongoDB instance
// Finally, pull documents from the remote instance and add them to MongoDB Mobile
client.getAuth().loginWithCredential(new AnonymousCredential())
   .addOnCompleteListener(new OnCompleteListener<StitchUser>() {
      @Override
      public void onComplete(@NonNull Task<StitchUser> task) {
         //get a remote client...
         final RemoteMongoClient atlasMongoClient =
            client.getServiceClient(RemoteMongoClient.factory, "mongodb-atlas");

         //...and the atlas collection
         RemoteMongoCollection remoteCollection = atlasMongoClient
            .getDatabase("my_db").getCollection("my_collection");

         //find all documents in the remote collection
         RemoteFindIterable cursor = remoteCollection.find();

         cursor.into(new ArrayList<Document>())
            .addOnCompleteListener(new OnCompleteListener() {
               @Override
               public void onComplete(@NonNull Task task) {
                  if (task.isSuccessful()) {
                     //iterate through all the returned docs and add them to the local
                     //collection
                     for (Document doc : (ArrayList<Document>) task.getResult()) {
                           String url = doc.getString("url_name");
                           localCollection.insertOne(doc);
                     }
                  } else {
                     Log.e("Stitch", "Error adding item", task.getException());
                  }
               }
         });
      }
   });
// Get a previously defined client
let client = Stitch.defaultAppClient!

// Log-in using an Anonymous authentication provider from Stitch
// Then create a connection to a remote MongoDB instance
// Finally pull documents from the remote instance and add them to MongoDB Mobile
client.auth.login(withCredential: AnonymousCredential()) { result in
      switch result {
      case .success:
         let atlasMongoClient = client.serviceClient(fromFactory: remoteMongoClientFactory, withName: "mongodb-atlas")

         let queryDoc = Document()

         atlasMongoClient.db("my_db").collection("my_collection")
            .find(queryDoc).asArray({ result in switch result {
            case .success(let result):
                  result.forEach({ document in
                     try localCollection.insertOne(document)
                  })
            case .failure(let error):
                  print("failed to find documents: \(error)")
                  }
            })
      case .failure(let error):
         print("failed to login: \(error)")
      }
}

Note

The latest SDKs require your Atlas cluster to be version 3.4 or higher.