用户的帖子数,默认值



假设我有一个数据

[
{
"_id": "629eb5ced774223d36a68907",
"userId": "629eb22698df1015e980a98f",
"posts": [
{
"_id": "629eb59ad774223d36a688fa",
"title": "titletestz",
"body": "bodyz",
"createdAt": "2022-06-07T02:19:06.314Z",
"updatedAt": "2022-06-07T02:19:06.314Z",
"__v": 0
},
{
"_id": "629eb59ad774223d36a688fc",
"title": "titletestx",
"body": "bodyx",
"createdAt": "2022-06-07T02:19:06.879Z",
"updatedAt": "2022-06-07T02:19:06.879Z",
"__v": 0
}
],
"createdAt": "2022-06-07T02:19:58.206Z",
"updatedAt": "2022-06-07T02:19:58.206Z",
"__v": 0
},
{
"_id": "629ebf8b775b5cd326b1c41c",
"userId": "629eb22698df1015e980a98f",
"posts": [
{
"_id": "629eb22c98df1015e980a995",
"title": "ttle3",
"body": "ttile3",
"createdAt": "2022-06-07T02:04:28.787Z",
"updatedAt": "2022-06-07T02:04:28.787Z",
"__v": 0
}
],
"createdAt": "2022-06-07T03:01:31.065Z",
"updatedAt": "2022-06-07T03:01:31.065Z",
"__v": 0
}
]

我想统计特定用户的帖子数

let start = new Date()
start = start.setHours(0,0,0,0)
let end = new Date()
end = start.setHours(23,59,59,999)
model.aggregate([
{
$match: {
userId,
createdAt: {
$gte: start,
$lt: end
}
}
},
{
$unwind : '$posts',
},
{
$count: 'count'
}
])

现在起作用了

[
{
"total": 3
}
]

然而,我想设置用户的0的默认值,如果它不包含任何帖子,像这样:

[
{
"total": 0
}
]

现在我只是有一个空数组[]的响应,如果用户没有任何帖子。

任何想法我怎么能实现这在蒙古使用聚合?

使用$facet$ifNull

mongo操场

db.collection.aggregate([
{
"$facet": {
count: [
{
$match: {
userId,
createdAt: {
$gte: start,
$lt: end
}
}
},
{ $unwind: "$posts" },
{ "$count": "total" }
]
}
},
{
"$project": {
"total": {
"$ifNull": [
{ "$arrayElemAt": ["$count.total", 0] },
0
]
}
}
}
])

您最好尽可能避免使用unwind。简单的方法就是$group$sum在每个文档上增加帖子的数量。如果该用户没有帖子,则返回0。如果需要,可以在多个用户同时运行

编辑:使用$facet解决没有文档的用户:

db.collection.aggregate([
{
$facet: {
count: [{
$match: {
userId,
createdAt: {$gte: start, $lt: end}
}
},
{$group: {_id: "$userId", total: {$sum: {$size: "$posts"}}}}
]},
{
$project: {
total: {$ifNull: [{$arrayElemAt: ["$count.total", 0]}, 0]}}
}
])

看看它在操场的例子中是如何工作的

如果不匹配则返回空数组。

let start = new Date()
start = start.setHours(0,0,0,0)
let end = new Date()
end = start.setHours(23,59,59,999);
db.collection.aggregate(
[
{
$match: {
userId,
createdAt: {
$gte: start,
$lt: end
}
}
},
{
$group: {
'$posts'
}
},
{
$count: "totalCount"
}
]
)

相关内容

最新更新