- SoapUI Cookbook
- Rupert Anderson
- 726字
- 2021-07-23 20:19:20
Querying MongoDB with Groovy
The simplicity and scalability of document-based or NoSQL databases has made them very popular. One of the most popular NoSQL databases is MongoDB (http://www.mongodb.org/). In this recipe, we learn how to query MongoDB by calling its API using a Groovy TestStep
.
Getting ready
If you don't already have MongoDB, then install it using the instructions on the main MongoDB site (http://docs.mongodb.org/manual/installation/). I am assuming that MongoDb will be running on the usual localhost
and port 27017
. By default, no authentication is required; this will be assumed in this recipe.
To access MongoDB from Groovy, you can use the MongoDB Java driver. However, Groovy users have the option of GMongo
, which simplifies the API nicely.
Note
GMongo
This is a convenient Groovy wrapper for the standard MongoDB driver. Note that the standard driver is still required. See https://github.com/poiati/gmongo.
Before using GMongo
, we need to download the JAR files, and add them to SoapUI. You can find the JAR files at Maven Central:
http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver/
http://mvnrepository.com/artifact/com.gmongo/gmongo
This recipe uses the latest versions (driver 2.12.3 and GMongo 1.3); add the JAR files to the following location:
<SoapUI Installation>/java/app/bin/ext
The completed SoapUI project GroovyMongoDB-soapui-project.xml
can be found in the Chapter2
samples.
How to do it…
Again, we'll use a Groovy TestStep
to run our example queries using the GMongo API. First, we'll create some test documents in MongoDB. Then, we will insert a query, update, and delete examples. Perform the following steps:
- First, let's create a couple of MongoDB documents in a database called
test
. Create aGroovy TestStep
and enter the following:import com.gmongo.GMongo def mongo = new GMongo() def db = mongo.getDB('test') db.invoices << [id: 'inv1', company: 'test company1', amount: '100.00'] db.invoices << [id: 'inv2', company: 'test company2', amount: '200.00']
- Next, we will see how to query the invoice documents. There are many ways to do this:
- Create a new
Groovy TestStep
and add the sameGMongo
database connection code (db) as in the preceding example. - Then, try the following statement:
//Get a single invoice object log.info db.invoices.findOne()
- This should give an output similar to the following code:
Thu Aug 28 11:42:02 BST 2014:INFO:{ "_id" : { "$oid" : "53fefc8b036476c440b3da8c"} , "amount" : "100" , "company" : "test company1" , "id" : "inv1"}
- Create a new
- Some other simple query examples are shown in the following code:
//Get a single invoice document with id=inv2 log.info db.invoices.findOne(id: 'inv2') //Get a single invoice document, excluding the object id (_id) db.invoices.findOne([:],[_id: 0]) //To iterate over all invoice documents db.invoices.find().each{invoice-> log.info invoice }
- To update documents, use the following query:
//Update invoice object with id=inv2 setting amount=500 db.invoices.update([id: 'inv2'], [$set: [amount: '500']])
- To delete documents, use the following query:
//Delete invoice ibject with id=inv1 db.invoices.remove([id: 'inv1']) //Delete ALL invoices db.invoices.remove([:])
How it works...
These are only simple and limited examples of what is possible. The GMongo
wrapper has provided default connectivity details and allowed us to focus on querying mongo. There was also very little to import and configure, and there was no need to manage the connection explicitly, for example, close it after use. If we need to connect to a different server and port, it's easy to do this using the constructor:
def mongo = new GMongo('localhost:27017')
Using the mongo query language is quite fun, but powerful! We have already seen how it will create a new database and collection data without any fuss just by referring to them using queries.
Tip
GMongo syntax differences
MongoDB syntax vs GMongo syntax - When looking up MongoDB commands, it's worth being mindful of the Groovy language changes that GMongo
or Groovy needs to make to the standard MongoDB equivalent syntax. For example, the MongoDB command syntax to exclude the Mongo object (_id
) from the query output is db.invoices.findOne({},{_id: 0})
, but with GMongo you would need to write this as db.invoices.findOne([:],[_id: 0])
. In other words, the MongoDB syntax uses curly brackets{}
, where GMongo would use square brackets []
. Also, the MongoDB uses empty curly brackets {}
to represent an empty Map, whereas GMongo or Groovy requires us to use the empty Map [:]
.syntax.
There's more...
To practice the queries and understand more about the way Mongo stores data, it's worth having a go with the MongoDB shell. Open a shell/command prompt and try the following code:
cd <mongo installation directory> ./bin/mongo (should connect you to the local instance) show dbs (should contain you 'test' database) use test (use database test for ongoing queries) show collections (should contain your 'invoices' collection) db.invoices.find() (should give the same results as before)
For more info, see http://docs.mongodb.org/manual/reference/mongo-shell/.
Note
Authentication
If you need authenticated access to MongoDB, consider using the GMongo
client class com.gmongo.GMongoClient
to get your connection (see https://github.com/poiati/gmongo for more details).
If you have a lot of test data that you would like to load into a collection separately to SoapUI, then take a look at the Mongo shell command mongoimport
in the installation bin
directory. See http://docs.mongodb.org/manual/reference/program/mongoimport/ for more details.
See also
- For more information on Mongo REST interfaces, go to http://docs.mongodb.org/ecosystem/tools/http-interfaces/
- UI圖標(biāo)創(chuàng)意設(shè)計
- Designing Machine Learning Systems with Python
- Git Version Control Cookbook
- 軟件項目管理(第2版)
- C/C++算法從菜鳥到達人
- 編程珠璣(續(xù))
- BeagleBone Media Center
- Instant Typeahead.js
- Java游戲服務(wù)器架構(gòu)實戰(zhàn)
- Learn Swift by Building Applications
- UML+OOPC嵌入式C語言開發(fā)精講
- Learning Python Design Patterns(Second Edition)
- 大數(shù)據(jù)分析與應(yīng)用實戰(zhàn):統(tǒng)計機器學(xué)習(xí)之?dāng)?shù)據(jù)導(dǎo)向編程
- Building Wireless Sensor Networks Using Arduino
- Programming with CodeIgniterMVC