mongoDB comparing date

被刻印的时光 ゝ 提交于 2020-08-11 18:49:31

问题


I am using spring mongoTemplate.I am trying to find Date of birth from min and max Date. My resultant query is

db.profile.find({ "$and" : [ { "dob" : { "$lte" : { "$date" : "2014-01-31T18:30:00.000Z"}}} , { "dob" : { "$gte" : { "$date" : "1995-01-31T18:30:00.000Z"}}}]}).pretty() 

but it didn't return any records.Where I am missing?


回答1:


All queries in MongoDB are and operations by default, so you don't need the wrapping $and here.

It is also the wrong way to do it, your serialization should look like this:

{ 
    "dob" : { 
        "$lte" : { "$date" : "2014-01-31T18:30:00.000Z"},
        "$gte" : { "$date" : "1995-01-31T18:30:00.000Z"}
    }
}

Or basically in the shell way:

db.collection.find({ 
    "dob" : { 
        "$lte" : new Date("2014-01-31"),
        "$gte" : new Date("1995-01-31")
    }
})

So both the $lte and $gte operations are part of the same BSON element.

Something like this with the query builder:

    DBObject query = new Query(
        Criteria.where("dob")
            .gte(new DateTime("1995-01-31").toDate())
            .lte(new DateTime("2014-01-31").toDate())
    ).getQueryObject();


来源:https://stackoverflow.com/questions/25132675/mongodb-comparing-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!