gpt4 book ai didi

java - MongoDB:使用 or 语句查询

转载 作者:行者123 更新时间:2023-11-29 04:46:33 25 4
gpt4 key购买 nike

MongoDB 版本 3.0.6

所以我有这个查询,我想在其中执行一些小于和大于操作。此外,我想执行 操作,但我无法弄清楚 java 中的语法。以下是我目前所拥有的:

FindIterable<Document> iterable3 = db.getCollection(collectionName).find(
new Document()
.append("timestamp", new Document()
.append("$gte", startTime)
.append("$lte", endTime))
.append("hourOfDay", new Document()
.append("$gte", minHourOfDay)
.append("$lte", maxHourOfDay))
.append("dayOfWeek", new Document()
.append("$or", new Document("2","4")))

);

我想要的是还检查 dayOfWeek 参数是否等于 24 的查询。

最佳答案

使用 $in 运算符如下:

db.collection.find({ 
"timestamp": { "$gte": startTime, "$lte": endTime },
"hourOfDay": { "$gte": minHourOfDay, "$lte": maxHourOfDay },
"dayOfWeek": { "$in": [2, 4] }
});

上面的查询是下面带有 $or 的查询的简单得多的版本运算符(operator):

db.collection.find({ 
"timestamp": { "$gte": startTime, "$lte": endTime },
"hourOfDay": { "$gte": minHourOfDay, "$lte": maxHourOfDay },
"$or": [
{ "dayOfWeek": 2 },
{ "dayOfWeek": 4 }
]
});

所以你最终的 Java 代码应该是这样的

FindIterable<Document> iterable3 = db.getCollection(collectionName).find(
new Document()
.append("timestamp", new Document()
.append("$gte", startTime)
.append("$lte", endTime))
.append("hourOfDay", new Document()
.append("$gte", minHourOfDay)
.append("$lte", maxHourOfDay))
.append("dayOfWeek", new Document("$in", Arrays.asList(2, 4)));
);

关于java - MongoDB:使用 or 语句查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36889281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com