使用给定的代码,我尝试连接到 mongo db,按事件类型选择事件,而不是断言我刚刚选择的内容
@Grab('org.mongodb:mongodb-driver:3.4.1')
import com.mongodb.MongoClient
import com.mongodb.MongoClientURI
import com.mongodb.DBCollection
import com.mongodb.DB
import com.mongodb.DBCursor;
import com.mongodb.BasicDBObject
import com.mongodb.DBObject;
import groovy.json.JsonSlurper;
class MongoService {
private MongoClient mongoClient
def login = "user"
def password = "pass"
def host = "host"
def port = port
def databaseName = 'mongodb'
public MongoClient client() {
mongoClient = new MongoClient(new MongoClientURI(
new StringBuilder("mongodb://").
append(login).append(":").
append(password).append("@").
append(host).append(":").
append(port).append("/").
append(databaseName).toString()))
;
return mongoClient
}
public DBCollection collection(collectionName) {
DB db = client().getDB(databaseName)
return db.getCollection(collectionName)
}
}
def service = new MongoService(databaseName: 'mongodb')
def foo = service.collection('events')
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("EventType", "test");
DBCursor cursor = foo.find(whereQuery);
while (cursor.hasNext()) {
log.info(cursor.next())
}
def json = cursor.next()
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(json)
assert result.EventType == "test"
我在第 52 行返回 soapui 返回 java.util.NoSuchElementException 错误,在 mongodb 中使用相同的查询手动检查db.getCollection('events').find({"EventType": "test"})
返回 1 个对象。我不知道如何使它工作......:/