MongoClient Range Query

94 views
Skip to first unread message

Guru Prasad

unread,
Nov 13, 2015, 1:45:30 PM11/13/15
to vert.x
I am using MongoClient to communicate with MongoDB from my verticle. I have a requirement where I am supposed to do a find() with a range query like latitude greater than 16.0445735678 and less than 16.08054643. Latitude is a field in one of MongoDB's collections.

Can someone please let me know how this can be achieved using Vert.x's MongoClient?

David Bush

unread,
Nov 14, 2015, 7:13:26 PM11/14/15
to vert.x
The query should be a JSON object that looks like this:

{"$and": [
 {"latitude": {"$gt": 16.0445735678}},
 {"latitude": {"$lt": 16.08054643}},
]}


Construct this in what ever language you are using and it will be your query parameter for the MongoClient find method.

In Java, I often use the MongoDb QueryBuilder for complicated queries. In this case it would be like this:

import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import io.vertx.core.json.JsonObject;

[...]

DBObject builder = new QueryBuilder().start()
    .and(
        new QueryBuilder().start().put("latitude").greaterThan(16.0445735678).get(),
        new QueryBuilder().start().put("latitude").lessThan(16.08054643).get()
    ).get();


JsonObject query = new JsonObject(builder.toMap());

mongoClient.find(COLLECTION_NAME, query, response -> {
 [handle the response]
});


The QueryBuilder also supports geo queries that may be of interest to you. I've never used that feature so you'll have to research it yourself. Here's the API:

Guru Prasad

unread,
Nov 15, 2015, 6:09:07 AM11/15/15
to vert.x
Thanks David. That helped.
Reply all
Reply to author
Forward
0 new messages