2017-05-24 58 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

哦,我不确定,我不是很熟悉猫鼬。 –