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. The following sections provide the steps necessary to get started.

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:

  • ARM32, ARM64, or x86-64
  • A device and image that can run ARM v8/v7
  • Boot option: Cold boot
  • 1GB RAM
  • 4GB internal storage
  • 1GB SD Card (Studio-managed)

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 prerequsites are met, you are ready to start building your mobile app.

Procedure

The following steps guide you through the process of adding MongoDB Mobile (Beta) to your 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 to the /src/main/jniLibs/<platform> folder, where <platform> is armeabi-v7a, arm64-v8a, or x86_64.
  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.0.0'
    implementation 'org.mongodb:stitch-android-services-mongodb-local:4.0.0'
    
  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

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

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

Your code 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
self.localCollection = try mongoClient.db(db).collection(col)
let result = try localcollection.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: remoteMongoDBServiceClientFactory, withName: "mongodb-atlas")

      atlasMongoClient.db("my_db").collection("my_collection")
         .find({}).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.