【发布时间】:2023-04-06 22:26:01
【问题描述】:
我的数据库中有集合,
[
{
"groupName" : "testName",
"participants" : [
{
"participantEmail" : "test@test.com",
"lastClearedDate" : 12223213123
},
{
"participantEmail" : "test2@test.com",
"lastClearedDate" : 1234343243423
}
],
"messages" : [
{
"message":"sdasdasdasdasdasd",
"time":22312312312,
"sender":"test@test.com"
},
{
"message":"gfdfvd dssdfdsfs",
"time":2231231237789,
"sender":"test@test.com"
}
]
}
]
这是一个组的集合,其中包含该组中的所有参与者和消息。 消息中的时间字段是时间戳。
我想获取在给定日期之后发布并按日期分组的组内的所有消息。 我写了以下代码,
ChatGroup.aggregate([
{ $match: { group_name: groupName } },
{ $unwind: "$messages" },
{ $match: { "messages.time": { $gte: messagesFrom } } },
{
$project: {
_id: 0,
y: {
$year: {
$add: [new Date(0), { $multiply: [1000, "$messages.time"] }]
}
},
m: {
$month: {
$add: [new Date(0), { $multiply: [1000, "$messages.time"] }]
}
},
d: {
$dayOfMonth: {
$add: [new Date(0), { $multiply: [1000, "$messages.time"] }]
}
}
}
},
{
$group: {
_id: {
year: "$y",
month: "$m",
day: "$d"
},
messages: { $push: "$messages" },
count: { $sum: 1 }
}
}
]).then(
group => {
console.log("length of messages", group);
resolve(group);
},
err => {
console.log(err);
}
);
});
我得到以下输出,
[
{
"_id": {
"year": 50694,
"month": 9,
"day": 5
},
"messages": [],
"count": 3
},
{
"_id": {
"year": 50694,
"month": 8,
"day": 27
},
"messages": [],
"count": 1
},
{
"_id": {
"year": 50694,
"month": 8,
"day": 26
},
"messages": [],
"count": 10
}
]
我没有收到消息,但计数是正确的。 结果中显示的时间也不正确,例如年、日期和月份。 Mongo 版本是 3.2。
我参考了来自 mongodb 的 groupby 和推送文档以及关于 mongo group by 的其他 stackoverflow 问题。
我做错了什么?
【问题讨论】:
-
删除
$multiply1000
标签: mongodb mongoose aggregation-framework