Bạn có thể sử dụng $cond nhà điều hành để kiểm tra xem:
-
$monthlà<= 3, chiếu một trường có tênquartervới giá trị là "một". -
$monthlà<= 6, chiếu một trường có tênquartervới giá trị là "hai". -
$monthlà<= 9, chiếu một trường có tênquartervới giá trị là "ba". - khác giá trị của trường
quartersẽ là "thứ tư". - Sau đó,
$groupbởiquarterlĩnh vực này.
Mã:
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" } } },
]);
Cụ thể cho lược đồ của bạn:
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" } } },
]);