简体   繁体   中英

Mongo DB + java query by date

I am very new to Mongo DB and using java mongo driver to get datas from mongo db from my java class.

I have a following rows in collection.

{
        "_id" : "13dded92-a9c0-48f8-9522-7422e2c7c2b6",
        "E_MAIL" : "Anonymous_User",
        "CITY" : "New York",
        "COUNTRY" : "USA",
        "OPERATING_SYSTEM" : "WINDOWS_10",
        "DATE_TIME" : "27-08-2016 09:47:17",
        "TOKEN" : "t76be55otr6galp4prc0f5k7bu"
}
{
        "_id" : "13dded92-a9c0-48f8-9522-7422e2c7c2b6",
        "E_MAIL" : "Anonymous_User",
        "CITY" : "New York",
        "COUNTRY" : "USA",
        "OPERATING_SYSTEM" : "WINDOWS_10",
        "DATE_TIME" : "27-08-2016 09:47:17",
        "TOKEN" : "t76be55otr6galp4prc0f5k7bu"
}
{
        "_id" : "13dded92-a9c0-48f8-9522-7422e2c7c2b6",
        "E_MAIL" : "Anonymous_User",
        "CITY" : "New York",
        "COUNTRY" : "USA",
        "OPERATING_SYSTEM" : "WINDOWS_10",
        "DATE_TIME" : "24-08-2016 09:47:17",
        "TOKEN" : "t76be55otr6galp4prc0f5k7bu"
}
{
        "_id" : "13dded92-a9c0-48f8-9522-7422e2c7c2b6",
        "E_MAIL" : "Anonymous_User"
        "CITY" : "New York",
        "COUNTRY" : "USA",
        "OPERATING_SYSTEM" : "WINDOWS_10",
        "DATE_TIME" : "22-08-2016 09:47:17",
        "TOKEN" : "t76be55otr6galp4prc0f5k7bu"
}

I am trying to group them by date,so this should give the result as 2 for date passed 27-08-2016

For this, I tried the following code in my java class.

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;

    import javax.mail.MessagingException;
    import javax.mail.internet.AddressException;

    import org.bson.Document;
    import org.bson.conversions.Bson;

    import com.mongodb.AggregationOutput;
    import com.mongodb.BasicDBObject;
    import com.mongodb.BasicDBObjectBuilder;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.DBObject;
    import com.mongodb.MongoClient;

    public class Same {
        public static void main(String[] args) throws AddressException, MessagingException {

            try {
                MongoClient mongoClient = new MongoClient("localhost", 27017);
                DBCollection collection;

                DB db = mongoClient.getDB("myDB");
                collection = db.getCollection("myCollection");

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy.MM.dd");
                String date ="2016.08.27"; 
                String date1 ="2016.08.27"; 
                Date startDate = simpleDateFormat.parse(date);  
                Date endDate = simpleDateFormat.parse(date1);
                BasicDBObject query1 = new BasicDBObject("LOGIN", new BasicDBObject("$gte",startDate).append("$lt",endDate ));
                collection.find(query1);

                System.out.println("count");
                System.out.println(collection.find(query1));

                mongoClient.close();

            } catch (Exception e) {
                System.err.println(e.getClass().getName() + ": " + e.getMessage());
            }

        }
    }

I am getting console as follows,

count
DBCursor{collection=DBCollection{database=DB{name='myDB'}, name='myCollection'}, find=FindOptions{, batchSize=0, limit=0, modifiers=null, projection=null, maxTimeMS=0, skip=0, sort=null, cursorType=NonTailable, noCursorTimeout=false, oplogReplay=false, partial=false}}

How to get the count value here, what I am really missing.

First of all, you are missing the classes in the current driver ;-)

Then, find returns an iterable or DBCursor (depending on the version), which needs to be iterated to yield useful documents. Those documents have to be read and analyzed.

And last, you probably don't want to use find() but count() if you are interested in the count only.

Example without resorting to deprecated stuff:

MongoCollection collection = mongoClient.getDatabase("myDB").getCollection("myCollection");
... (prepare dates)
Bson query = Filters.and(
                Filters.gte("fieldName", startDate),
                Filters.lt("fieldName", endDate));
System.out.println(collection.count(query));

Edit: one additional thing: your documents hold the dates as strings , thus comparing them to dates will not work. Make sure you also use Date-objects when saving the data. When you query these via mongo shell they should look like ISODate('2016-09-27T13:17:05.000Z') when everything was correct.

You are using the same dates for $gt and lt .

This means your query searches the datas in between the date range as follows,

{ "LOGIN" : 
    { "$gte" : { "$date" : "2016-08-27T18:30:00.000Z"} , 
      "$lt" : { "$date" : "2016-08-27T18:30:00.000Z"}
    }
}

This returns nothing.

Try to reduce a date in Start Date like below

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy.MM.dd");
            String date ="2016.08.26"; 
            String date1 ="2016.08.27"; 
            Date startDate = simpleDateFormat.parse(date);  
            Date endDate = simpleDateFormat.parse(date1);

This should works for you and returns data.

You can change the timings to match as per your pattern.

    startDate .setHours(0);
    startDate .setMinutes(0);

Hope this helps.

Since you are using BasicDBObject I think you are working with mongo-java-driver-2.14.2 or older. However to run properly your query you have to assign it to a cursor:

DBCursor cursor = coll.find(query1);

Now you can iterate over this cursor:

try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

Now probably your query is not right for your target. If you want to retrieve the number of documents referenced by your cursor, maybe you can use:

BasicDBObject query1 = new BasicDBObject("fieldName", new BasicDBObject("$gte",startDate).append("$lt",endDate ));

long count = db.collection.find(query1).count()
System.out.println("count: " + count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM