gpt4 book ai didi

mongodb - 如何向 Mongo 聚合结果添加新字段?

转载 作者:可可西里 更新时间:2023-11-01 09:20:39 24 4
gpt4 key购买 nike

我有以下 mongodb 聚合查询,按日期分组(1-05-2017 到 1-13-2017)

CampaignActivity.aggregate([
{
"$match": {
"$and":[{updatedAt: {$lt: new Date('1-13-2017')}},{updatedAt: {$gte: new Date('1-05-2017')}}]
}
},
{
"$project" :
{
_id : 0,
"datePartDay" : {"$concat" : [
{"$substr" : [{"$dayOfMonth" : "$updatedAt"}, 0, 2]}, "-",
{"$substr" : [{"$month" : "$updatedAt"}, 0, 2]}, "-",
{"$substr" : [{"$year" : "$updatedAt"}, 0, 4]}
] },
"isdelivered": {"$cond": { if: { $eq: [ "$delivered", true ] }, then: 1, else: 0 }},
"isclicked": {"$cond": { if: { $eq: [ "$clicked", true ] }, then: 1, else: 0 }},
"isunsubscribe": {"$cond": { if: { $eq: [ "$unsubscribed", true ] }, then: 1, else: 0 }}

}
},

{ "$group" :
{ "_id" : "$datePartDay",
"delivered" : { "$sum" :'$isdelivered' },
"clicked" : { "$sum" :'$isclicked' },
"unsubscribed" : { "$sum" :'$isunsubscribe' }
}
}
],function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});

聚合结果:

 [
{
"_id": "12-1-2017",
"delivered": 0,
"clicked": 1,
"unsubscribed": 1
},
{
"_id": "11-1-2017",
"delivered": 2,
"clicked": 1,
"unsubscribed": 0
}
]
  • 是否可以添加新字段以导致集合中不存在诸如“日期”之类的内容?

  • 是否可以使用虚拟数据添加缺失的日期字段?

最佳答案

您的$project 阶段是多余的。您可以轻松地将所有逻辑移至 $group 阶段并以 $project 阶段结束以重新格式化您的响应。

像下面这样的东西。

[{
"$match": {
"$and": [{
updatedAt: {
$lt: new Date('1-13-2017')
}
}, {
updatedAt: {
$gte: new Date('1-05-2017')
}
}]
}
}, {
"$group": {
"_id": {
$dateToString: {
format: "%m-%d-%Y",
date: "$updatedAt"
}
},
"delivered": {
$sum: {
"$cond": {
if: {
$eq: ["$delivered", true]
},
then: 1,
else: 0
}
}
},
"clicked": {
$sum: {
"$cond": {
if: {
$eq: ["$clicked", true]
},
then: 1,
else: 0
}
}
},
"unsubscribed": {
$sum: {
"$cond": {
if: {
$eq: ["$unsubscribed", true]
},
then: 1,
else: 0
}
}
}
}
}, {
"$project": {
"_id": 0,
"date": "$_id",
"delivered": 1,
"clicked": 1,
"unsubscribed": 1
}
}]

关于mongodb - 如何向 Mongo 聚合结果添加新字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41592999/

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