如何使用groovy将值存储在mongodb集合中某个字段的变量中?

时间:2019-11-06 09:16:07

标签: mongodb groovy jmeter

我已成功在收藏夹中插入了一个新文档。现在,我想读取同一文档并提取其“ _id”,并将其存储在变量中,以供下一个采样器使用。我的脚本失败

    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",12345)
            //.append("EmployeeOID",12345)
            .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("TRGEmpID","012345T");

        collection.insertOne(document);


    Document result = collection.find(eq("EmployeeOID",12345)).first();

    def ID = result.get("_id").toString()); 
        return "Document inserted"+result.get(ID);

        }
    catch (Exception e) {
        SampleResult.setSuccessful(false);
        SampleResult.setResponseCode("500");
        SampleResult.setResponseMessage("Exception: " + e);
    }

错误:

Response code: 500
Response message: javax.script.ScriptException: 
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed:
Script219.groovy: 31: expecting '}', found ')' @ line 31, column 38.
   def ID = result.get("_id").toString());  
                                        ^

1 个答案:

答案 0 :(得分:0)

只需更改此行:

def ID = result.get("_id").toString());

对此:

def ID = result.get("_id").toString()

如果您还想将值保存到JMeter Variable中,则可以按以下方式进行操作:

vars.put('ID', ID)

一旦完成,您将能够在JSR223脚本中将值恢复为vars.get('ID')或在其他测试元素中将其恢复为${ID}

演示:

enter image description here

更多信息:MongoDB Performance Testing with JMeter