官术网_书友最值得收藏!

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.

Tip

MongoDB as a service backend

Since MongoDB stores data as documents using the (Binary JSON) or BSON format, it can be convenient for use as a service or a mock backend when JSON data is required.

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:

  1. First, let's create a couple of MongoDB documents in a database called test. Create a Groovy 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']

    Note

    Running the preceding script should

    Create a new GMongo instance connected to the local MongoDB install, host=localhost and port=27017

    Use a database called test if one exists, or create the database

    Insert two new invoice documents into a new or existing collection called invoices

  2. 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 same GMongo 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"}
  3. 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
    }
  4. To update documents, use the following query:
    //Update invoice object with id=inv2 setting amount=500
    db.invoices.update([id: 'inv2'], [$set: [amount: '500']])
  5. 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

主站蜘蛛池模板: 唐山市| 班玛县| 龙山县| 河曲县| 错那县| 盐津县| 洪湖市| 惠州市| 罗平县| 新乐市| 搜索| 西贡区| 甘德县| 章丘市| 松江区| 怀安县| 色达县| 尼勒克县| 安西县| 洪湖市| 印江| 常德市| 保亭| 铜陵市| 保亭| 上饶市| 喀什市| 康定县| 阿拉善盟| 河源市| 依安县| 昭通市| 鹤壁市| 双牌县| 阿克苏市| 沧源| 台南市| 辽中县| 无为县| 益阳市| 上饶县|