【问题标题】:MongoDB: Query with an or statementMongoDB:使用 or 语句进行查询
【发布时间】:2016-04-27 12:04:34
【问题描述】:

MongoDB 3.0.6 版

所以我有这个查询,我想在其中执行一些小于和大于操作。另外,我想执行一个or 操作,但我无法弄清楚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

【问题讨论】:

标签: java mongodb


【解决方案1】:

使用 $in 运算符,如下所示:

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

上面的查询是以下查询的一个更简单的版本,带有$or 运算符:

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)));
);  

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多