Created
March 25, 2014 02:39
-
-
Save jyemin/9754316 to your computer and use it in GitHub Desktop.
This test shows that range queries over a date work properly both with and without the use of $and operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.mongodb.BasicDBObject; | |
import com.mongodb.DBCollection; | |
import com.mongodb.DBObject; | |
import com.mongodb.MongoClient; | |
import com.mongodb.QueryBuilder; | |
import java.net.UnknownHostException; | |
import java.util.Date; | |
public class AndQueryTest { | |
public static void main(String[] args) throws UnknownHostException { | |
MongoClient client = new MongoClient(); | |
DBCollection collection = client.getDB("test").getCollection("test"); | |
Date d = new Date(); | |
BasicDBObject document = new BasicDBObject("myColumn", "myValue").append("myDate", d); | |
System.out.println("Inserting: " + document); | |
collection.insert(document); | |
DBObject simpleQuery = QueryBuilder.start("myColumn").is("myValue") | |
.and("myDate").greaterThan(new Date(d.getTime() - 1)).lessThan( new Date(d.getTime() + 1)) | |
.get(); | |
System.out.println(); | |
System.out.println("Simple query: " + simpleQuery); | |
System.out.println(collection.findOne(simpleQuery)); | |
DBObject andQuery = QueryBuilder.start("myColumn").is("myValue") | |
.and(new BasicDBObject("myDate", new BasicDBObject("$gt", | |
new Date(d.getTime() - 1))), | |
new BasicDBObject("myDate", new BasicDBObject("$lt", | |
new Date(d.getTime() + 1)))) | |
.get(); | |
System.out.println(); | |
System.out.println("$and query: " + andQuery); | |
System.out.println(collection.findOne(andQuery)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Inserting: { "myColumn" : "myValue" , "myDate" : { "$date" : "2014-03-25T02:35:33.719Z"}} | |
Simple query: { "myColumn" : "myValue" , "myDate" : { "$gt" : { "$date" : "2014-03-25T02:35:33.718Z"} , "$lt" : { "$date" : "2014-03-25T02:35:33.720Z"}}} | |
{ "_id" : { "$oid" : "5330eb75b0c6bc2ea11d13e7"} , "myColumn" : "myValue" , "myDate" : { "$date" : "2014-03-25T02:35:33.719Z"}} | |
$and query: { "myColumn" : "myValue" , "$and" : [ { "myDate" : { "$gt" : { "$date" : "2014-03-25T02:35:33.718Z"}}} , { "myDate" : { "$lt" : { "$date" : "2014-03-25T02:35:33.720Z"}}}]} | |
{ "_id" : { "$oid" : "5330eb75b0c6bc2ea11d13e7"} , "myColumn" : "myValue" , "myDate" : { "$date" : "2014-03-25T02:35:33.719Z"}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment