Search code examples
mongodbgroovyjmeteraggregatemongodb-java

Perform Mongodb Aggregation in JMeter


I'm trying to run a simple aggregation in JMeter using the the mongo-java-driver 3.8. I'm new to JMeter and using Mongo with Java. I used this tutorial as a starting point:

https://www.blazemeter.com/blog/mongodb-performance-testing-with-jmeter/

I modified the code from the Querying Documents section for use in the JSR223 Sampler as follows:

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.client.model.Aggregates;

try {
    MongoCollection<Document> collection = vars.getObject("collection");

    Document result = collection.aggregate(Arrays.asList(Aggregates.sample(1)));

    vars.put("exampleDocumentId", result.get("_id").toString());

    return "Document with id=" + result.get("_id") + " found";
}
catch (Exception e) {
    SampleResult.setSuccessful(false);
    SampleResult.setResponseCode("500");
    SampleResult.setResponseMessage("Exception: " + e);
}

I get the following error in response for the Sampler result in the View Results tree:

Response code: 500
Response message: Exception: org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object 'com.mongodb.client.internal.AggregateIterableImpl@3c7a0022' with class
'com.mongodb.client.internal.AggregateIterableImpl' to class 'org.bson.Document'

Solution

  • Collection.aggregate() function call returns AggregateIterable which cannot be cast to the document directly, you can use Groovy head() method which returns the first value from the Iterable instance like:

    Document result = collection.aggregate(Arrays.asList(Aggregates.sample(1))).head()
    

    More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It