The query is an aggregation which converts the string date values to Date
values. The result list from the aggregation is iterated and the modified documents are updated in a for-loop. Note the code assumes a collection with multiple input documents.
The Java Code:
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.MongoDatabase;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.model.WriteModel;
import com.mongodb.bulk.BulkWriteResult;
import java.util.*;
public class MongoReact {
public static void main(String[] args)
throws Throwable {
MongoClient mongoClient = MongoClients.create();
MongoDatabase db = mongoClient.getDatabase("testdb");
MongoCollection<Document> collection = db.getCollection("test");
List<Bson> pipeline =
Arrays.asList(
new Document("$project",
new Document("fTwo.nestedFObject.anotherDateF",
new Document("$dateFromString",
new Document("dateString", "$fTwo.nestedFObject.anotherDateF")
)
)
.append("fTwo.nestedFArray",
new Document("$map",
new Document("input", "$fTwo.nestedFArray")
.append("as", "e")
.append("in",
new Document("dateF",
new Document("$dateFromString",
new Document("dateString", "$$e.dateF")
)
)
)
)
)
)
);
SubscriberHelpers.ObservableSubscriber<Document> querySubscriber =
new SubscriberHelpers.ObservableSubscriber<Document>();
collection.aggregate(pipeline).subscribe(querySubscriber);
querySubscriber.await();
List<Document> resultDocs = querySubscriber.getReceived();
List<WriteModel<Document>> updates = new ArrayList<>();
for (Document doc : resultDocs) {
ObjectId id = (ObjectId) doc.get("_id");
Document f2Doc = (Document) doc.get("fTwo");
updates.add(new UpdateOneModel<Document>(
new Document("_id", id),
new Document("$set", new Document("fTwo", f2Doc))
));
}
SubscriberHelpers.PrintSubscriber<BulkWriteResult> updateSubscriber =
new SubscriberHelpers.PrintSubscriber<BulkWriteResult>("Bulk write results: %s");
collection.bulkWrite(updates).subscribe(updateSubscriber);
updateSubscriber.await();
mongoClient.close();
}
}
NOTES:
The SubscriberHelpers
is a utility class used in the above code. I have used it as shown in the Quick Tour (with examples) section of the Reactive Streams Java Driver page.
The source code for the SubscriberHelpers.java
can be found at: mongo-java-driver-reactivestreams/examples/tour/src/main/tour/. The usage of the code and examples source code is also there - you can compile and use it.
I have used MongoDB server 4.0, Java SE 8, MongoDB Reactive Streams driver 1.10.0 and mongodb-driver-async 3.9.0 to work with the above code.