【发布时间】:2021-05-26 21:58:24
【问题描述】:
这是我第一次使用aggregate pipeline。我无法让“$match”表达式在管道内工作。如果我删除“_id”匹配项,我会得到集合中的每个文档都超过了开始日期,但是一旦我添加了$eq 表达式,它就会返回空。
我阅读了很多其他示例并尝试了许多不同的方法,这似乎是正确的。但是结果是空的。
有什么建议吗?
let now = new Date()
let doc = await Team.aggregate([
{ $match: { created_by: mongoose.Types.ObjectId(req.params.user_oid)} },
{ $sort: { create_date: 1 } },
{ $lookup: {
from: 'events',
let: { "team_oid": "$team_oid" },
pipeline: [
{ $addFields: { "team_oid" : { "$toObjectId": "$team_oid" }}},
{ $match: {
$expr: {
$and: [
{ $gt: [ "$start", now ] },
{ $eq: [ "$_id", "$$team_oid" ] }
]
},
}
},
{
$sort: { start: 1 }
},
{
$limit: 1
}
],
as: 'events',
}},
{
$group: {
_id: "$_id",
team_name: { $first: "$team_name" },
status: { $first: "$status" },
invited: { $first: "$invited" },
uninvited: { $first: "$uninvited" },
events: { $first: "$events.action" },
dates: { $first: "$events.start" } ,
team_oid: { $first: "$events.team_oid" }
}
}])
示例文档(按要求添加)
活动:
_id:ObjectId("60350837c57b3a15a414d265")
invitees:null
accepted:null
sequence:7
team_oid:ObjectId("60350837c57b3a15a414d263")
type:"Calendar Invite"
action:"Huddle"
status:"Questions Issued"
title:"Huddle"
body:"This is a Huddle; you should receive new questions 5 days befor..."
creator_oid:ObjectId("5ff9e50a206b1924dccd691e")
start:2021-02-26T07:00:59.999+00:00
end:2021-02-26T07:30:59.999+00:00
__v:0
团队:
_id:ObjectId("60350837c57b3a15a414d263")
weekly_schedule:1
status:"Live"
huddle_number:2
reminders:2
active:true
created_by:ObjectId("5ff9e50a206b1924dccd691e")
team_name:"tESTI"
create_date:2021-02-23T13:50:47.172+00:00
__v:0
【问题讨论】:
-
您能否发布“事件”和“团队”的示例文档或架构?
-
我添加了文档。我看到你也发布了一个答案,但它消失了..?
-
我重新安装了它。它在下面。我添加了一个游乐场只是为了确保它正常工作。我认为这应该是你的解决方案。
-
哈哈,我已经测试过了,效果很好!!谢谢老哥
-
太好了,非常欢迎您!
标签: mongodb mongoose aggregate pipeline