Navigation

Remotely Access MongoDB

Overview

Query data stored in MongoDB directly from your client application code with the MongoDB query language by using MongoDB Realm’s MongoClient. MongoDB Realm provides data access rules for collections to securely retrieve results based on the logged-in user or the content of each document.

Prerequisites

Before you can remotely access mongodb, you must:

Use the MongoClient to Query For Data in Your Collection

Note

The following code snippet requires that the user is already authenticated.

// mongodb-atlas is the cluster service name
let client = app.currentUser!.mongoClient("mongodb-atlas")

// Select the database
let database = client.database(named: "tracker")

// Select the collection
let collection = database.collection(withName: "Task")
 
// Using the user's id to look up tasks
let user = app.currentUser!
let identity = user.id

// Run the query
collection.find(filter: ["_partition": AnyBSON(identity)], { (result) in
    // Note: this completion handler may be called on a background thread.
    //       If you intend to operate on the UI, dispatch back to the main
    //       thread with `DispatchQueue.main.async {}`.
    switch result {
    case .failure(let error):
        // Handle errors
        print("Call to MongoDB failed: \(error.localizedDescription)")
        return
    case .success(let documents):
        // Print each document
        print("Results:")
        documents.forEach({(document) in
            print("Document:")
            document.forEach({ (key, value) in
                print("  key: \(key), value: \(value!)")
            })
        })
    }
})
←   Sync Data Call a Function  →