MongoDB Mobile

MongoDB Mobile is the mobile version of the MongoDB database. It's aimed at smartphones and IoT sensors via Embedded MongoDB. MongoDB Mobile has two core parts:

  • A MongoDB database server that runs locally on the device, enabling offline access to data. This database is a stripped-down version of the MongoDB Server Community Edition, without any of the features that are not needed for Mobile (for example, replication).
  • Native Java and Android SDKs to provide low-level access to the database and interact with the local Mobile database and any MongoDB Stitch backend.

Mobile SDK has two modes of operation. In local mode, the SDK only allows access to the local Mobile database, and cannot sync with any external source in Atlas. In remote mode, the SDK can access both MongoDB Atlas and MongoDB Mobile databases and Sync between them.

Here are some limitations of MongoDB Mobile over the server version:

  • No support for replication
  • No support for sharding
  • No database authentication; however, the MongoDB Mobile database only accepts connections originating from the application
  • No SSL
  • No encryption at rest
  • No change streams support
  • No server-side JavaScript evaluation (this is for performance reasons)
  • No multi-document ACID transactions

To set up MongoDB Mobile, we need to download and install the MongoDB Stitch SDK first. Then, creating and querying a local MongoDB database is as easy as a few lines of code (this example is in Android):

Import 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;

Initialize the database as follows:

// 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);

Next, get a reference to the database:

MongoCollection<Document> localCollection =
mobileClient.getDatabase("my_db").getCollection("my_collection");

Insert document as follows:

localCollection.insertOne(document);

Then, find the first document by using first():

Document doc = localCollection.find().first();

MongoDB Mobile is most powerful when used in conjunction with MongoDB Stitch, which we will explore in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset