2016-03-04 81 views
0

我想創建mongodb在春季數據可選查詢,但獲取錯誤。任何人都可以請幫我解決這個問題。需要幫助mongodb查詢之間可選參數

請注意此查詢是日期範圍

之間下面是查詢

@Query(value = "{ $and: [ 
        {$or : [ { $where: '?0 == null' } , { createdDate : {$gt : ?0} }]}, 
        {$or : [ { $where: '?1 == null' } , { createdDate : {$lt : ?1} }]} 
] }") 

下面是生成的查詢

{ "$and" : [ 
{ "$or" : [ { "$where" : "{ \"$date\" : \"2016-02-28T18:30:00.000Z\"} == null"} , 
{ "createdDate" : { "$gt" : { "$date" : "2016-02-28T18:30:00.000Z"}}}]} , 

{ "$or" : [ { "$where" : "{ \"$date\" : \"2016-03-11T18:30:00.000Z\"} == null"} , 
{ "createdDate" : { "$lt" : { "$date" : "2016-03-11T18:30:00.000Z"}}}]} 
]} 

得到以下錯誤

org.springframework.data.mongodb.UncategorizedMongoDbException: { "serverUsed" : "localhost:27017" , "waitedMS" : 0 , "ok" : 0.0 , "errmsg" : "Failed to call method" , "code" : 1}; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "waitedMS" : 0 , "ok" : 0.0 , "errmsg" : "Failed to call method" , "code" : 1} 
+0

很抱歉,但你真的失去了我這裏,而且大多因爲你試圖在正確的語法是如此不正確,很難確定你的意思。 ['$ where']是一個接受JavaScript函數以在文檔選擇標準中解析爲「true/false」的參數。這不是你在做什麼。也許在再次詢問文檔之前仔細看看文檔 –

+0

也不是這種'@ Query'用法在spring-mongo中的粉絲。我認爲這只是迎合了那些在休眠中使用類似簽名屬性的人,但並不知道他們的意思。具有「對象」參數的9/10情況是,您最好只是檢查通常比在對象的方法調用中嘗試合理化命名參數。 –

+0

如果上述查詢令人困惑,請致歉。我正在嘗試編寫查詢以獲取日期範圍內的記錄。如果只有startdate存在,那麼我需要所有在startdate之後創建的記錄,並且如果只有todate禮物,那麼我只需要所有在todate之前創建的記錄。如果兩者都失蹤,那麼我需要所有的記錄。這是我想要做的。 – OneTwo

回答

1

您的查詢也不是很清楚,但是從我的理解(基於0和1插值和你的意見?):

@Query(value = "{ $or: [ 
        {$and : [ { toDate: { $exists: false } } , { startDate: { $exists: true } }, { createdDate : {$gt : ?0} }]}, 
        {$and : [ { toDate: { $exists: true } }, { startDate: { $exists: false } } , { createdDate : {$lt : ?1} }]}, 
        {$and : [ { toDate: { $exists: false } }, { startDate: { $exists: false } } 
] }")