问题
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