Skip to content

Instantly share code, notes, and snippets.

@hennasingh
Created May 23, 2022 20:06
Embed
What would you like to do?
public class AirbnbActivity extends AppCompatActivity {
String appID = "Your APP ID";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airbnb);
Realm.init(this);
App app = new App(new AppConfiguration.Builder(appID).build());
app.loginAsync(Credentials.anonymous(), result -> {
if (result.isSuccess()) {
Log.v("QUICKSTART", "Successfully authenticated anonymously.");
User user = app.currentUser();
MongoClient mongoClient =
user.getMongoClient("mongodb-atlas"); // service for MongoDB Atlas cluster containing custom user data
MongoDatabase mongoDatabase =
mongoClient.getDatabase("sample_airbnb");
MongoCollection<Document> mongoCollection =
mongoDatabase.getCollection("listingsAndReviews");
Log.v("EXAMPLE", "Successfully instantiated the MongoDB collection handle");
Document queryFilter = new Document("price", 80.00);
//Read a Single Document
mongoCollection.findOne(queryFilter).getAsync(task -> {
if (task.isSuccess()) {
Document resultBack = task.get();
// Log.d("EXAMPLE","Count found is " + resultBack.size());
Log.d("EXAMPLE", "successfully found a document: " + resultBack);
} else {
Log.e("EXAMPLE", "failed to find document with: ", task.getError());
}
});
// Read Multiple Documents
Document readMultiple = new Document("property_type", "House");
RealmResultTask<MongoCursor<Document>> findTask = mongoCollection.find(readMultiple).iterator();
findTask.getAsync(task -> {
if (task.isSuccess()) {
MongoCursor<Document> results = task.get();
Log.v("EXAMPLE", "successfully found all properties of type House:");
while (results.hasNext()) {
Log.d("EXAMPLE", results.next().toString());
}
} else {
Log.e("EXAMPLE", "failed to find documents with: ", task.getError());
}
});
//Update Query
Document updateFilter = new Document("name", "Ribeira Charming Duplex");
Document updateDocument = new Document("$set", new Document("bedrooms", 4));
mongoCollection.updateOne(updateFilter, updateDocument).getAsync(task -> {
if (task.isSuccess()) {
long count = task.get().getModifiedCount();
if (count == 1) {
Log.v("EXAMPLE", "successfully updated a document.");
} else {
Log.v("EXAMPLE", "did not update a document.");
}
} else {
Log.e("EXAMPLE", "failed to update document with: ", task.getError());
}
});
} else{
Log.e("QUICKSTART", "Failed to log in. Error: " + result.getError());
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment