[英]Group documents by month in MongoDB
現在我有一個Mongoose查詢,看起來像
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()
,但是由於我正在使用.find()
進行過濾,使用.sort()
排序,使用.select()
字段選擇以及使用.populate()
。
每個文檔都有字段date
,因此可能類似於
Collection
.find( selector )
.aggregate([
{ $project: { month: { $month: $date }, year: { $year },
{ $group: { _id: { $month: $date, $year: $date }, docs: { $push: '' } }
])
無需'$ project',因為您也可以在$group
使用month方法
因此,您將獲得類似以下內容的信息:
$group:{
_id : { year: { $year: "$date" }, month: { $month: "$date" } },
docs: { $push: { field1: "$field1", field2: "$field1" } }
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.