I could connect Jmeter to MongoDB successfully but inserting document to Mongo DB fails. Note that I Am able to insert the document directly to Mongo using same credentials.
Successfully Connected to Mongo by following code:
import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClient; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.Arrays; try { String mongoUser = vars.get("mongouser"); String userDB = vars.get("userdb"); char[] password = vars.get("password").toCharArray(); MongoCredential credential = MongoCredential.createCredential(mongoUser, userDB, password); MongoClientSettings settings = MongoClientSettings.builder() .applyToClusterSettings {builder -> builder.hosts(Arrays.asList(new ServerAddress(InetAddress.getByName(vars.get("mongoHost")), vars.get("mongoPort").toInteger())))} .build(); MongoClient mongoClient = MongoClients.create(settings); MongoDatabase database = mongoClient.getDatabase(vars.get("databaseName")); MongoCollection<Document> collection = database.getCollection(vars.get("collectionName")); vars.putObject("collection", collection); return "Connected to " + vars.get("collectionName"); } catch (Exception e) { SampleResult.setSuccessful(false); SampleResult.setResponseCode("500"); SampleResult.setResponseMessage("Exception: " + e); }
In another sampler as follow I Am trying to Add a document to MongoDB:
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import static com.mongodb.client.model.Filters.*;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.Arrays;
try {
MongoCollection<Document> collection = vars.getObject("collection");
Document document = new Document("EmployeeOID",1111111)
.append("EmployeeName", "Test Automation through Jmeter")
.append("Employee_Type_OID",4)
.append("Rank",0)
.append("Rating",0)
.append("Score",0)
.append("Supervisor_OID",56789)
.append("EmpID","222222T");
collection.insertOne(document);
Document result = collection.find(eq("EmployeeOID",1111111)).first();
if(result !=null){
String ID =result.get("_id");
log.info(ID)
ObjectId objectId = new ObjectId(ID);
vars.put('myID', objectId as String);
log.info (vars.get('myID'))
return ;
}
return "Employee not found";
}
catch (Exception e) {
SampleResult.setSuccessful(false);
SampleResult.setResponseCode("500");
SampleResult.setResponseMessage("Exception: " + e);
}
which fails with Error:
Response code: 500 Response message: Exception: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]