1

MongoDB version 3.0.6

So I have this query where I want to perform some less than and greater than operations. Additionally, I want perform an or operation, but I can't figure out the syntax for that in java. Below is what I have so far:

FindIterable<Document> iterable3 = db.getCollection(collectionName).find(
    new Document()
        .append("timestamp", new Document()
               .append("$gte", startTime)
               .append("$lte", endTime))
        .append("hourOfDay", new Document()
                .append("$gte", minHourOfDay)
                .append("$lte", maxHourOfDay))
        .append("dayOfWeek", new Document()
                .append("$or", new Document("2","4")))

);

What I want is the query to also check if the dayOfWeek parameter is either equal to 2 or 4.

kongshem
  • 322
  • 1
  • 5
  • 23
  • have a look at this http://stackoverflow.com/questions/10620771/how-can-i-build-an-or-query-for-mongodb-using-the-java-driver – piyushj Apr 27 '16 at 12:11

1 Answers1

3

Use the $in operator as follows:

db.collection.find({ 
    "timestamp": { "$gte": startTime, "$lte": endTime },
    "hourOfDay": { "$gte": minHourOfDay, "$lte": maxHourOfDay },
    "dayOfWeek": { "$in": [2, 4] }
});

The above query is a much simpler version of the following query with the $or operator:

db.collection.find({ 
    "timestamp": { "$gte": startTime, "$lte": endTime },
    "hourOfDay": { "$gte": minHourOfDay, "$lte": maxHourOfDay },
    "$or": [
        { "dayOfWeek": 2 },
        { "dayOfWeek": 4 }
    ]
});

So your final Java code would look like

FindIterable<Document> iterable3 = db.getCollection(collectionName).find(
    new Document()
        .append("timestamp", new Document()
               .append("$gte", startTime)
               .append("$lte", endTime))
        .append("hourOfDay", new Document()
                .append("$gte", minHourOfDay)
                .append("$lte", maxHourOfDay))
        .append("dayOfWeek", new Document("$in", Arrays.asList(2, 4)));
);  
chridam
  • 100,957
  • 23
  • 236
  • 235