gpt4 book ai didi

mongodb - Mongo聚合查询计算多个计算值

转载 作者:可可西里 更新时间:2023-11-01 10:15:39 25 4
gpt4 key购买 nike

鉴于以下文件。

{
_id: 1,
ExpirationDate: ISODate("2017-05-02T09:29:46.006+0000")
}
{
_id: 2,
ExpirationDate: ISODate("2017-05-12T09:29:46.006+0000")
}
{
_id: 3,
ExpirationDate: ISODate("2017-05-23T09:29:46.006+0000")
}

如何使用聚合管道计算以下输出?

{
"NumberOfSubscriptionExpiringToday": 12,
"NumberOfSubscriptionExpiringWithInAWeek": 4
}

我希望只用一个查询而不是两个来完成这一任务。这是我到目前为止所拥有的...

.aggregate([
{
$match: {
"ExpirationDate": {
$gte: ISODate("2017-05-02T00:00:00.000+0000"),
$lte: ISODate("2017-05-03T00:00:00.000+0000")
}
}
},
{
$project: {
_id: 1
}
},
{
$count: "ExpiringToday"
}
]);


.aggregate([
{
$match: {
"ExpirationDate": {
$gte: ISODate("2017-05-02T00:00:00.000+0000"),
$lte: ISODate("2017-05-08T00:00:00.000+0000")
}
}
},
{
$project: {
_id: 1
}
},
{
$count: "ExpiringInSevenDays"
}
]);

最佳答案

您可以使用 $cond 在单个聚合查询中执行此操作运算符检查每个文档的到期日期是否在 [today, tomorrow) 范围内,或在 [tomorrow, weekAfterToday) 范围内:

var today = ISODate("2017-05-04T00:00:00.000");
var tomorrow = ISODate("2017-05-05T00:00:00.000");
var weekAfterToday = ISODate("2017-05-11T00:00:00.000");

db.collection.aggregate([
{ $match: { "ExpirationDate": { $gte: today, $lt: weekAfterToday }}},
{
$project: {
ExpiringToday: {
$cond: {
if: {
$and: [
{$gte: ["$ExpirationDate",today]},
{$lt:["$ExpirationDate",tomorrow]}
]
}, then: 1, else: 0
}
},
ExpiringInAWeek: {
$cond: { if: {$gte: ["$ExpirationDate",tomorrow]}, then: 1, else: 0 }
}
}
},
{ $group: {
_id: 1,
NumberOfSubscriptionExpiringToday: {$sum: "$ExpiringToday" },
NumberOfSubscriptionExpiringWithInAWeek: {$sum: "$ExpiringInAWeek" }
}
},
{ $project: { _id: 0 }}
]);

还考虑提出两个简单的请求:

var numberOfSubscriptionExpiringToday = db.collection.count(
{ "ExpirationDate": { $gte: today, $lt: tomorrow }}
);

var numberOfSubscriptionExpiringWithInAWeek = db.collection.count(
{ "ExpirationDate": { $gte: tomorrow , $lt: weekAfterToday }}
);

关于mongodb - Mongo聚合查询计算多个计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43787258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com