Skip to content

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);


This is how you do it:

import org.bson.json.JsonObject;
// ...
String json = """

List<BsonDocument> pipeline = new BsonArrayCodec().decode(new JsonReader(json), DecoderContext.builder().build())

MongoClient client = new MongoClient();

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

for (JsonObject cur: results) {