kongshem
kongshem

Reputation: 332

MongoDB: Query using $gte and $lte in java

I want to perform a query on a field that is greater than or equal to, AND less than or equal to(I'm using java btw). In other words. >= and <=. As I understand, mongoDB has $gte and $lte operators, but I can't find the proper syntax to use it. The field i'm accessing is a top-level field.

I have managed to get this to work:

FindIterable<Document> iterable = db.getCollection("1dag").find(new Document("timestamp", new Document("$gt", 1412204098)));

as well ass...

FindIterable<Document> iterable = db.getCollection("1dag").find(new Document("timestamp", new Document("$lt", 1412204098)));

But how do you combine these with each other?

Currently I'm playing around with a statement like this, but it does not work:

FindIterable<Document> iterable5 = db.getCollection("1dag").find(new Document( "timestamp", new Document("$gte", 1412204098).append("timestamp", new Document("$lte",1412204099))));

Any help?

Upvotes: 3

Views: 16590

Answers (2)

Philipp
Philipp

Reputation: 69663

The constructor new Document(key, value) only gets you a document with one key-value pair. But in this case you need to create a document with more than one. To do this, create an empty document, and then add pairs to it with .append(key, value).

Document timespan = new Document();
timespan.append("$gt", 1412204098);
timespan.append("$lt", 1412204998);
// timespan in JSON: 
// { $gt: 1412204098, $lt: 1412204998}
Document condition = new Document("timestamp", timespan);
// condition in JSON:
// { timestamp: { $gt: 1412204098, $lt: 1412204998} }

FindIterable<Document> iterable = db.getCollection("1dag").find(condition);

Or if you really want to do it with a one-liner without temporary variables:

FindIterable<Document> iterable = db.getCollection("1dag").find(
    new Document()
        .append("timestamp", new Document()
             .append("$gt",1412204098)
             .append("$lt",1412204998)
        )
);

Upvotes: 3

chridam
chridam

Reputation: 103375

Basically you require a range query like this:

db.getCollection("1dag").find({
    "timestamp": {
        "$gte": 1412204098,
        "$lte": 1412204099
    }
})

Since you need multiple query conditions for this range query, you can can specify a logical conjunction (AND) by appending conditions to the query document using the append() method:

FindIterable<Document> iterable = db.getCollection("1dag").find(
        new Document("timestamp", new Document("$gte", 1412204098).append("$lte", 1412204099)));

Upvotes: 9

Related Questions