【问题标题】:mongodb query: result with conditional findmongodb查询:有条件查找的结果
【发布时间】:2019-06-14 00:21:16
【问题描述】:

我正在尝试在 MongoDB 中进行条件查找。 给定一个包含以下字段的集合:

itemId: Long
itemName: String
unconsumed: Boolean
snooze: Boolean
expiryTs: Long

我想根据它们是否为unconsumed 来查找所有项目,具体取决于snooze,expiryTs 应该有条件地评估,如下所示:

if (snooze)
    expiryTs < now + 1
else
    expiryTs < now + 2

我使用 KMongo 来查询集合,但是使用以下查询

collection.find(and(PantryDomain::unconsumed eq true,
                    expr(cond(PantryDomain::snooze eq true,
                              PantryDomain::expiryTs lt Instant.now().plus(1, ChronoUnit.DAYS).toEpochMilli(),
                              PantryDomain::expiryTs lt Instant.now().plus(2, ChronoUnit.DAYS).toEpochMilli()))))

我收到此错误:

com.mongodb.MongoQueryException: Query failed with error code 16020 and error message 'Expression $lt takes exactly 2 arguments. 1 were passed in.' on server localhost:27017

知道查询有什么问题吗?谢谢:-)

【问题讨论】:

    标签: mongodb mongodb-query kmongo


    【解决方案1】:

    你可以试试

    collection.find(and(PantryDomain::unconsumed eq true,
                        expr(cond(PantryDomain::snooze eq true,
                                  lt PantryDomain::expiryTs Instant.now().plus(1, ChronoUnit.DAYS).toEpochMilli(),
                                  lt PantryDomain::expiryTs Instant.now().plus(2, ChronoUnit.DAYS).toEpochMilli()))))
    

    你也可以简化为

    collection.find(and(PantryDomain::unconsumed,
                        expr(cond(PantryDomain::snooze,
                                  lt PantryDomain::expiryTs Instant.now().plus(1, ChronoUnit.DAYS).toEpochMilli(),
                                  lt PantryDomain::expiryTs Instant.now().plus(2, ChronoUnit.DAYS).toEpochMilli()))))
    

    【讨论】:

    • 不幸的是,这不起作用,因为一旦lt 是一个中缀函数infix fun &lt;T&gt; KProperty&lt;T&gt;.lt(item: T): Bson = Filters.lt(path(), item) 简化也不起作用,但这不是问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2016-02-07
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多