Skip to content
Advertisement

How to use a JSON file to aggregate in MongoDB in Java?

I am using the Java MongoDB driver v4.3:

implementation group: 'org.mongodb', name: 'mongodb-driver-sync', version: '4.3.1'
implementation group: 'org.mongodb', name: 'bson', version: '4.3.1'

I have my aggregation pipelines written in JSON files which are placed in the src/main/resources folder. The aggregate function only accepts a List<Bson>. After fetching the file, how do I pass it into the MongoDB method?

String fileName = "physics/test.json";
File file = new File(fileName);
MongoDatabase db = mongoClient.getDatabase(DATABASE_NAME);
MongoCollection collection = db.getCollection(collectionName);
// Convert file to List<Bson> ???
AggregateIterable sourceList = collection.aggregate(pipeline);

Advertisement

Answer

This is how you do it:

import org.bson.json.JsonObject;
// ...
    
String json = """
        [{"$group":{"_id":{"segment":"$segment","invoice_id":{"$trim":{"input":"$invoice_id"}}},"qty":{"$sum":"$qty"}}}]""";

List<BsonDocument> pipeline = new BsonArrayCodec().decode(new JsonReader(json), DecoderContext.builder().build())
        .stream().map(BsonValue::asDocument)
        .collect(Collectors.toList());

MongoClient client = new MongoClient();

List<JsonObject> results = client.getDatabase("test").getCollection("test").withDocumentClass(JsonObject.class)
        .aggregate(pipeline).into(new ArrayList<>());

for (JsonObject cur: results) {
    System.out.println(cur.getJson());
}

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement