2017-05-24 62 views
0

組文件現在我有一個貓鼬查詢它看起來像按月MongoDB中

Collection 
    .find(selector) 
    .sort(sortCriteria) 
    .select(selectCriteria) 
    .populate(populateCriteria1) 
    .populate(populateCriteria2) 
    .then(docs => ...) 
    .catch(errHandler) 

所以我做了很多我的查詢。

我收藏中的每個文檔都有一個日期。我希望按月份和年份歸還文件。因此,它應該成爲什麼樣

docs = [ 
    { _id: { year: 2017, month: 4 }, docs: [ ... ] }, 
    { _id: { year: 2017, month: 5 }, docs: [ ... ] }, 
    { _id: { year: 2017, month: 6 }, docs: [ ... ] } 
] 

我想這是一個簡單的.aggregate(),但我不知道我應該包括它,因爲我使用的.select()做使用.find()篩選,排序使用.sort(),字段選擇,並填充使用.populate()

每個文檔都有現場date,所以它可能是這樣的

Collection 
    .find(selector) 
    .aggregate([ 
    { $project: { month: { $month: $date }, year: { $year }, 
    { $group: { _id: { $month: $date, $year: $date }, docs: { $push: '' } } 
    ]) 

回答

0

無需「$項目」,因爲你還可以在$group

使用一個月方法所以,你會得到像這樣:

$group:{ 
    _id : { year: { $year: "$date" }, month: { $month: "$date" } }, 
    docs: { $push: { field1: "$field1", field2: "$field1" } } 
    }} 
+0

謝謝,但我可以一起做'填充()'?你寫'$ push:{field1:...'。是否有可能只是說它應該推動我選擇的所有領域? – Jamgreen

+0

哦,我不確定,我不是很熟悉貓鼬。 –