2016-08-08 16 views
0

我正在使用MongoDB作爲我的環迴應用程序的數據源。因爲我必須檢索當月的文件。MongoDb在環迴應用程序中的Month比較查詢

,所以我嘗試了以下內容:

app.models.aaaa.count({ $where : 'return this.Date.getMonth() == 7'}, function(err, res){ 
}); 

現在我想根據今年和用戶id也進行過濾。我怎樣才能構建查詢。

我試過如下:

app.models.aaaa.count({ $where : 'return this.Date.getMonth() == 7 && this.Date.getYear() == 2016'}, function(err, res){ 
    }); 

但它僅檢查month..Please分享您的想法。在此先感謝

編輯:

[ 
    { 
    "aaaId": "57a84a572b9a79022198c6dd", 
    "bbId": "876hjg786", 
    "Date": "2016-08-08T00:00:00.000Z", 
    "cccc": [ 
     "57a1bfd0c77554fd746a538d'", 
     "57a1bfebc77554fd746a538f" 
    ], 
    "id": "57a85e1d9841c9cb1b100f21" 
    }, 
    { 
    "aaaId": "57a84a572b9a79022198c6dd", 
    "bbId": "876hjg786", 
    "Date": "2016-08-08T00:00:00.000Z", 
    "cccc": [ 
     "57a1bfd0c77554fd746a538d'", 
     "57a1bfebc77554fd746a538f" 
    ], 
    "id": "57a85f1d1605d9f11b4d21b3" 
    } 
] 
+0

你可以舉一個數據庫中的文檔的例子嗎? –

+0

你可以使用聚合框架嗎?它會更快。 – evilive

+0

@evilive你可以發佈一些代碼? – Subburaj

回答

0

這應該工作:

db.myCollection.count( 
    function() { 
    return (this.Date.getMonth() == 7 && this.Date.getYear() == 2016); 
    } 
); 

請注意,如果你只有一個$where,你可以只寫JavaScript函數作爲.count()說法,或者只是表達式如下:

db.myCollection.count("this.Date.getMonth() == 7 && this.Date.getYear() == 2016"); 
+0

我收到錯誤'AssertionError:其中參數必須是一個對象' – Subburaj

0

使用aggregation framework個項目和匹配文檔:如果你需要從原始文檔的某些字段只是形容他們在project階段

{ "_id" : ObjectId("57a86cbe8357264ce0b55b2b"), "m" : 8, "y" : 2016 } 

collection.aggregate(
    {$project: { 
    month: {$month: "$Date"}, 
    year: {$year: "$Date"} 
    }}, 
    {$match: {month: 8, year: 2016}} 
); 

,你會得到這樣的事情。

使用聚合必須更有效,然後使用where