为了设置场景,我想要生成的查询类似于我手动编写的以下查询。我的想法是我想从结果集中排除日期范围。在这种情况下,今天什么都没有,但如果过去或将来有的话,我想要它们!
{
"createdOn": {
$not: {
"$lte": ISODate("2020-20-23T23:59:59.999999999"),
"$gte": ISODate("2020-20-23T00:00"),
}
}
}
我用来尝试获取上述内容的代码如下:
Criteria.where("createdOn")
.not()
.gte(LocalDate.now().atTime(LocalTime.MIN))
.lte(LocalDate.now().atTime(LocalTime.MAX))
但是,这会生成以下内容:
{
"createdOn": {
"$not": {
"$gte": {
"$java": "2020-03-23T00:00"
}
},
"$lte": {
"$java": "2020-03-23T23:59:59.999999999"
}
}
}
如果我更改代码以在 lte
之前添加另一个 not
,它仍然会产生相同的输出。
有什么方法可以生成我想要的查询,或者有其他方法可以从结果集中排除一定范围的日期吗?
最佳答案
我尝试了您的 mongo
shell 和 MongoDB Spring Java 代码。 shell 代码工作正常,但使用 not()
的相应 Java 代码不起作用(我不知道为什么)。
这是使用您正在寻找的相同功能的另一种方法:
...nothing from today, but if there's any in the past or in the future
我正在使用以下输入文档:
{ _id: 1, createdOn: ISODate("2020-03-21T12:05:00") },
{ _id: 2, createdOn: ISODate("2020-03-28T18:33:00") },
{ _id: 3, createdOn: ISODate("2020-03-24T01:56:00") }
并且,假设今天的日期:ISODate("2020-03-24T02:50:04.992Z")
,结果应排除带有 _id 的文档: 3
,其中 createdOn
是在今天内。
mongo
shell 查询:
db.collection.find( {
$or: [
{ createdOn: { $gt: ISODate("2020-03-24T23:59:59.99") } },
{ createdOn: { $lt: ISODate("2020-03-24T00:00:00") } }
]
} )
这将返回带有 _id
的 1
和 2
的文档(这些文档不包括今天的日期)。
对应的Java代码:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s");
Date fromDate = dateFormat.parse("2020-03-24 00:00:00");
Date toDate = dateFormat.parse("2020-03-24 23:59:59");
Criteria c = new Criteria().orOperator(
Criteria.where("createdOn").lt(fromDate),
Criteria.where("createdOn").gt(toDate) );
Query q = Query.query(c);
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testDB");
List<Document> result = mongoOps.find(q, Document.class, "collection");
result.forEach(doc -> System.out.println(doc.toJson()));
关于java - 如何使用 spring data Criteria 构建器组合 "not"运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60819805/