jojacafe
7/18/2016 - 11:40 AM

Java mongodb async driver https://github.com/mongodb/mongo-java-driver/blob/3.0.x/driver-async/src/examples/tour/QuickTour.java

https://docs.mongodb.com/manual/reference/operator/update/

Array

Operators

Name	Description
$ Acts as a placeholder to update the first element that matches the query condition in an update.
$addToSet	Adds elements to an array only if they do not already exist in the set.
$pop	Removes the first or last item of an array.
$pullAll	Removes all matching values from an array.
$pull	Removes all array elements that match a specified query.
$pushAll	Deprecated. Adds several items to an array.
$push	Adds an item to an array.
MongoClient mongoClient = MongoClients.create(new ConnectionString("mongodb://localhost"));
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("test");

CompletableFuture<String> resultado = new CompletableFuture<String>();

try
{
  Document filter = new Document(){{
      append("_id", code);
      append("Name", "Name test");
  }};

  // Array
  Document doc = new Document(){{
      append("Providers", new Document().append("Code", "GTA1").append("Name", "GTA Name1"));
  }};

  // Insert _id, Name, Providers --> if not exist, push new
  collection.updateOne(filter, new Document("$addToSet", doc), new UpdateOptions().upsert(true), (updateResult, throwable) -> {
    System.out.println("Insertado!");
      
    resultado.complete(code);
  });
}
catch (Exception ex)
{
  System.out.println(ex.getMessage());

}

resultado.get();