Ris*_*arg 10 mongoose mongodb-query
我有一个包含日期的文件,我想按季度分组文件.我怎么能在MongoDB中做到这一点?
我的架构是:
var ekgsanswermodel = new mongoose.Schema({
userId: {type: Schema.Types.ObjectId},
topicId : {type: Schema.Types.ObjectId},
ekgId : {type: Schema.Types.ObjectId},
answerSubmitted :{type: Number},
dateAttempted : { type: Date},
title : {type: String},
submissionSessionId : {type: String}
});
Run Code Online (Sandbox Code Playgroud)
第一季度包含第1,2,3个月.第二季度包含第4季度,第5季度,第6季度等第4季度.我的最终答案应该是:
"result" : [
{
_id: {
quater:
},
_id: {
quater:
},
_id: {
quater:
},
_id: {
quater:
}
}
Run Code Online (Sandbox Code Playgroud)
Bat*_*eam 17
您可以使用$cond运算符来检查是否:
$month是<= 3,项目名为场quarter与价值"一".$month是<= 6,项目名为场quarter与价值"二".$month是<= 9,项目名为场quarter与价值"三".quarter将是"第四".$group由quarter现场.码:
db.collection.aggregate([
{$project:{"date":1,
"quarter":{$cond:[{$lte:[{$month:"$date"},3]},
"first",
{$cond:[{$lte:[{$month:"$date"},6]},
"second",
{$cond:[{$lte:[{$month:"$date"},9]},
"third",
"fourth"]}]}]}}},
{$group:{"_id":{"quarter":"$quarter"},"results":{$push:"$date"}}}
])
Run Code Online (Sandbox Code Playgroud)
特定于您的架构:
db.collection.aggregate([
{$project:{"dateAttempted":1,"userId":1,"topicId":1,"ekgId":1,"title":1,
"quarter":{$cond:[{$lte:[{$month:"$dateAttempted"},3]},
"first",
{$cond:[{$lte:[{$month:"$dateAttempted"},6]},
"second",
{$cond:[{$lte:[{$month:"$dateAttempted"},9]},
"third",
"fourth"]}]}]}}},
{$group:{"_id":{"quarter":"$quarter"},"results":{$push:"$$ROOT"}}}
])
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方法按季度对文档进行分组。
{
$project : {
dateAttempted : 1,
dateQuarter: {
$trunc : {$add: [{$divide: [{$subtract: [{$month:
"$dateAttempted"}, 1]}, 3]}, 1]}
}
}
}
Run Code Online (Sandbox Code Playgroud)