Tom
Tom

Reputation: 6332

How to query over multiple fields in mongoDB with the Java client

I want to query against a condition that the string concatenation of two fields is larger that a given value,something like the following,but I don't know how to write the queryCondition. Could someone help on this?

long t = 1479690653366;
String id = "5832499d63594c3b24030c19";

//There are _id and time fields in the document
DBCollection collection = ...
collection.find(<queryCondition>);

The logic of <queryCondition> is to find the documents whose concatenation of _time and _id column is larger than the concatenation of time and id, that is 14796906533665832499d63594c3b24030c19

Upvotes: 1

Views: 6123

Answers (1)

marmor
marmor

Reputation: 28179

I don't think you need string concatenation here.

You want docs that have _time > 1479690653366, as well as docs that have _time == 1479690653366, but only if their _id > 5832499d63594c3b24030c19.

In that case you can query:

collection.find({ $or : [ 
    _time : { $gt : 1479690653366}, 
    { _time : "1479690653366", _id : { $gt : ObjectId("5832499d63594c3b24030c19") } } 
]});

Or in Java syntax, something like:

DBObject or_part1 = new BasicDBObject("_time", new BasicDBObject("$gt", 1479690653366));
DBObject or_part2 = new BasicDBObject("_time", 1479690653366).append("_id", new BasicDBObject("$gt", new ObjectId("5832499d63594c3b24030c19")));
BasicDBList or = new BasicDBList();
or.add(or_part1);
or.add(or_part2);
DBObject query = new BasicDBObject("$or", or);
collection.find(query);

Upvotes: 3

Related Questions