Search code examples
javamongodbmongodb-querymongodb-javamongodate

MongoDB Java driver - date query


I am new to MongoDB and Java and I am trying to retrieve data from MongoDB using a date field.

Data:

{
    "_id" : {
        "timeSlice" : [ 
            2018, 
            5, 
            1
        ],
        "type" : "TRANSMISSION",
        "@objectName" : "SettlementInstance"
    },
    "Versions" : [ 
        {
            "id" : "dc57888a-c070-465f-9f2d-cbc5f2b69a09",
            "status" : "ACTIVE",
            "version" : NumberLong(10007)
        }
    ]
}

MongoDB query I use:

db.getCollection('SettlementInstance').find({"_id.timeSlice" : [2018,5,1]})

How to use this date field in Java with SQUARE Brackets and Integer dates together?

Any suggestion will be really helpful.


Solution

  • The following code will find the document you supplied in your question:

    // 3.x driver idiom
    Bson filter = Filters.eq("_id.timeSlice", Arrays.asList(2018, 5, 1));
    
    // 2.x driver idiom
    // Bson filter = new BasicDBObject("_id.timeSlice", Arrays.asList(2018, 5, 1));
    
    collection.find(filter);