mongodb查询:有条件查找的结果

时间:2019-01-20 11:22:34

标签: mongodb mongodb-query kmongo

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

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

我想根据是否为unconsumed来找到所有项目,并根据snooze找到有条件评估的到期时间,例如:

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

您知道查询出了什么问题吗?谢谢:-)

1 个答案:

答案 0 :(得分:0)

你能尝试

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