mongo = MongoClient.createShared(vertx, new JsonObject().put("db_name", "demo")); mongo.find("users", new JsonObject(), lookup -> { mongo.findOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), null, lookup -> { JsonObject newUser = ctx.getBodyAsJson(); mongo.findOne("users", new JsonObject().put("username", newUser.getString("username")), null, lookup -> { mongo.insert("users", newUser, insert -> { mongo.findOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), null, lookup -> { user.put("address", update.getString("address")); mongo.replace("users", new JsonObject().put("_id", ctx.request().getParam("id")), user, replace -> { mongo.findOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), null, lookup -> { } else { mongo.remove("users", new JsonObject().put("_id", ctx.request().getParam("id")), remove -> {
.put("db_name", db); MongoClient mongoClient = MongoClient.createShared(vertx, mongoconfig); mongoClient.save("products", product1, id -> { System.out.println("Inserted id: " + id.result()); mongoClient.find("products", new JsonObject().put("itemId", "12345"), res -> { System.out.println("Name is " + res.result().get(0).getString("name")); mongoClient.remove("products", new JsonObject().put("itemId", "12345"), rs -> { if (rs.succeeded()) { System.out.println("Product removed ");
private void loadData(MongoClient db) { db.dropCollection("users", drop -> { if (drop.failed()) { throw new RuntimeException(drop.cause()); } List<JsonObject> users = new LinkedList<>(); users.add(new JsonObject() .put("username", "pmlopes") .put("firstName", "Paulo") .put("lastName", "Lopes") .put("address", "The Netherlands")); users.add(new JsonObject() .put("username", "timfox") .put("firstName", "Tim") .put("lastName", "Fox") .put("address", "The Moon")); for (JsonObject user : users) { db.insert("users", user, res -> { System.out.println("inserted " + user.encode()); }); } }); } }
MongoClient mongo = MongoClient.createShared(vertx, config); Void v = awaitResult(h -> mongo.createCollection("users", h)); String id = awaitResult(h -> mongo.insert("users", user, h)); System.out.println("Inserted id is " + id); List<JsonObject> results = awaitResult(h -> mongo.find("users", new JsonObject(), h)); System.out.println("Retrieved " + results.size() + " results");
mongo = MongoClient.createShared(vertx, new JsonObject().put("db_name", "demo"));
final MongoClient mongo = MongoClient.createShared(vertx, new JsonObject().put("db_name", "demo")); mongo.find("users", new JsonObject(), lookup -> { mongo.insert("users", user, lookup -> { mongo.removeOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), lookup -> {
@Override public MongoAuth createProvider(Vertx vertx) { MongoClient client; if (shared) { if (datasourceName != null) { client = MongoClient.createShared(vertx, config, datasourceName); } else { client = MongoClient.createShared(vertx, config); } } else { client = MongoClient.createNonShared(vertx, config); } JsonObject authConfig = new JsonObject(); MongoAuthOptionsConverter.toJson(this, authConfig); return MongoAuth.create(client, authConfig); }
private void listAlbums(Message<JsonObject> msg) { // issue a find command to mongo to fetch all documents from the "albums" collection. mongo.find("albums", new JsonObject(), lookup -> { // error handling if (lookup.failed()) { msg.fail(500, lookup.cause().getMessage()); return; } // now convert the list to a JsonArray because it will be easier to encode the final object as the response. final JsonArray json = new JsonArray(); for (JsonObject o : lookup.result()) { json.add(o); } msg.reply(json); }); }
@Override public MongoService insert(String collection, JsonObject document, Handler<AsyncResult<String>> resultHandler) { client.insert(collection, document, resultHandler); return this; }
private void initMongoClient(Handler<AsyncResult<Void>> handler) { try { Vertx vertx = getVertx(); JsonObject config = getConfig(); LOGGER.info("STARTING MONGO CLIENT with config " + config); mongoClient = shared ? MongoClient.createShared(vertx, config) : MongoClient.createNonShared(vertx, config); if (mongoClient == null) { handler.handle(Future.failedFuture(new InitException("No MongoClient created"))); } else { mongoClient.getCollections(resultHandler -> { if (resultHandler.failed()) { LOGGER.error("", resultHandler.cause()); handler.handle(Future.failedFuture(resultHandler.cause())); } else { LOGGER.info(String.format("found %d collections", resultHandler.result().size())); handler.handle(Future.succeededFuture()); } }); } } catch (Exception e) { handler.handle(Future.failedFuture(new InitException(e))); } }
@Override public MongoService findOne(String collection, JsonObject query, JsonObject fields, Handler<AsyncResult<JsonObject>> resultHandler) { client.findOne(collection, query, fields, resultHandler); return this; }
private void populateDatabase(Collection<Place> places) { MongoClient mongo = MongoClient.createShared(vertx, new JsonObject().put("db_name", "places").put("connection_string", mongoURL), "places"); places.stream().forEach(place -> mongo.insert("places", place.toJson(), result -> { if (result.failed()) { System.err.println("I was not able to insert '" + place.getName() + "' : " + result.cause().getMessage()); } else { System.out.println("Place '" + place.getName() + "' inserted"); } })); }
private void initCounterCollection(Handler<AsyncResult<Void>> handler) { LOGGER.info("Init of sequence collection with " + collectionName); mongoClient.count(collectionName, referenceQuery, result -> { if (result.failed()) { handler.handle(Future.failedFuture(result.cause())); } else { long count = result.result(); if (count == 0) { LOGGER.info("Inserting initial sequence record into collection " + collectionName); this.mongoClient.insert(collectionName, referenceQuery, insertResult -> { if (result.failed()) { handler.handle(Future.failedFuture(insertResult.cause())); } else { LOGGER.info(result); handler.handle(Future.succeededFuture()); } }); } else { LOGGER.info("Record exists already"); handler.handle(Future.succeededFuture()); } } }); }
private void placeOrder(Message<JsonObject> msg) { mongo.save("orders", msg.body(), save -> { // error handling if (save.failed()) { msg.fail(500, save.cause().getMessage()); return; } msg.reply(new JsonObject()); }); }
public StoreCRUDServiceImpl(Vertx vertx, JsonObject config) { this.client = MongoClient.createNonShared(vertx, config); }
@Override public void updateModules(String id, SortedMap<String, Boolean> enabled, Handler<ExtendedAsyncResult<Void>> fut) { JsonObject jq = new JsonObject().put("_id", id); cli.find(COLLECTION, jq, gres -> { if (gres.failed()) { logger.debug("disableModule: find failed: " + gres.cause().getMessage()); fut.handle(new Failure<>(INTERNAL, gres.cause())); } else { List<JsonObject> l = gres.result(); if (l.isEmpty()) { logger.debug("disableModule: not found: " + id); fut.handle(new Failure<>(NOT_FOUND, messages.getMessage("1100", id))); } else { JsonObject d = l.get(0); final Tenant t = decodeTenant(d); t.setEnabled(enabled); JsonObject document = encodeTenant(t, id); cli.save(COLLECTION, document, sres -> { if (sres.failed()) { logger.debug("TenantStoreMongo: disable: saving failed: " + sres.cause().getMessage()); fut.handle(new Failure<>(INTERNAL, sres.cause())); } else { fut.handle(new Success<>()); } }); } } }); }
/** * Remove a single matching document from a collection and return the handler with MongoClientDeleteResult result * @param collection the collection * @param query query used to match document * @param resultHandler will be called when complete * @return */ public io.vertx.rxjava.ext.mongo.MongoClient removeDocument(String collection, JsonObject query, Handler<AsyncResult<MongoClientDeleteResult>> resultHandler) { delegate.removeDocument(collection, query, resultHandler); return this; }
@Override protected void onClose() { service.close(); } }
static Future<JsonObject> findOneAndReplace(final String collection, final JsonObject filter, final JsonObject updated) { // Find first for field update return Ux.thenGeneric(future -> CLIENT.findOne(collection, filter, null, handler -> { if (handler.succeeded()) { final JsonObject data = handler.result().mergeIn(updated); CLIENT.findOneAndReplace(collection, filter, data, result -> { LOGGER.debug(Info.MONGO_UPDATE, collection, filter, data); future.complete(data); }); } else { future.complete(updated); } })); }
@Test public void testWithSugar() throws InterruptedException { Record record = MongoDataSource.createRecord("some-mongo-db", new JsonObject().put("connection_string", "mongodb://localhost:12345"), new JsonObject().put("database", "some-raw-data")); discovery.publish(record, r -> { }); await().until(() -> record.getRegistration() != null); AtomicBoolean success = new AtomicBoolean(); MongoDataSource.getMongoClient(discovery, new JsonObject().put("name", "some-mongo-db"), ar -> { MongoClient client = ar.result(); client.getCollections(coll -> { client.close(); success.set(coll.succeeded()); }); }); await().untilAtomic(success, is(true)); } }