簡體   English   中英

與范圍內的空日期進行比較

[英]Compare with null Date in range

@Document
public class Product extends Item {
    private Date onlineDate;

    private Date offlineDate;
}

數據

Product {
    onlineDate : some date
    offlineDate : null
}

下面的查詢返回 0 個命中

query.addCriteria(Criteria.where("onlineDate").lte(date).and("offlineDate").gte(date))

但下面的查詢返回結果

query.addCriteria(Criteria.where("onlineDate").lte(date))

這是我不允許與空日期進行比較的東西。

您基本上需要在結果中包含接受null條件。 現在你問的是“大於”提供的日期,而null不是“大於”,因此它被排除在外。

這意味着添加一個$or條件來測試該字段上的兩種可能條件:

Criteria criteria = Criteria.where("onlinedate").lte(date).orOperator(
    Criteria.where("offlinedate").gte(date),
    Criteria.where("offlinedate").is(null)
);

Query query = new Query().addCriteria(criteria);

System.out.println(query.getQueryObject());

這會給你:

{ 
    "onlinedate" : { "$lte" : date } , 
    "$or" : [ 
        { "offlinedate" : { "$gte" : date } } , 
        { "offlinedate" :  null }
    ]
}

這是更改查詢以允許null值的正確翻譯,但它確實讓我認為您對查詢的基本想法是不正確的,因為這將返回基本上說“仍然在線”的結果 這可能是您想要的,但您可能一直打算提出不同的要求。

事實上,如果你正在尋找“全能”的文件,並沒有附帶的date值“betweeen”文檔中的兩個值,那么你就不是“反轉”的范圍則表達式匹配“之間”的文檔,然后選擇“反轉”結果用$nor代替:

Criteria criteria = new Criteria().norOperator(
   Criteria.where("onlinedate").gte(date)
   .and("offlinedate").lte(date)
);

Query query = new Query().addCriteria(criteria);

System.out.println(query.getQueryObject());

這會導致這樣的查詢:

{
    "$nor" : [ 
        { 
            "onlinedate" : { "$gte" : date }, 
            "offlinedate" : { "$lte" : date }
        }
    ]
}

它返回兩個日期屬性之間范圍“之前”和“之后”的結果,或者"offline"日期為null且范圍未“關閉”的地方。

這取決於您實際想要的結果集,要么包含null值以查找“仍然打開”的數據,要么您只是“排除范圍”以查找超出范圍的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM