Mongodb如果然后在过滤条件下如何制作 [英] Mongodb if then condition under filter how to make
本文介绍了Mongodb如果然后在过滤条件下如何制作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}
},
{
$project: {
"History": {
$filter: {
input: "$History",
as: "his",
if: {
$eq: [
"5e4a8d2d3952132a08ae5764",
"$$his.user_id"
]
},
then: {
cond: {
$and: [
{
$lt: [
"$$his.date",
"$date"
]
},
{
$eq: [
"5e4a8d2d3952132a08ae5764",
"$$his.user_id"
]
}
]
}
},
else: {}
}
},
data: 1,
history_id: 1,
sender_id: 1,
text: 1,
date: 1
}
},
{
$unwind: "$History"
}
])
在过滤条件出错的情况下播放if条件.我的目的是指定user_id与历史记录的user_id匹配,然后以其他方式匹配条件.
Play with if condition under filter getting error. My purpose is specified user_id match with history's user_id then condition work other wise not.
如何解决它,请指导或欢迎采用其他方法.
How to fix it please guide or alternative approaches are welcome.
推荐答案
在聊天中讨论之后,似乎总的问题是如何根据相关历史文档的2个标准从主集合中选择文档:
After discussion in chat, it seems the overall problem was how to select documents from the main collection based on 2 criteria of the related history documents:
db.main.aggregate([
{$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}},
{$match: {
$expr: {
$eq: [
false,
{$reduce: {
input: "$History",
initialValue: false,
in: {
$or: [
"$$value",
{$and: [
{$eq: [
"$$this.user_id",
ObjectId("5e4a8d2d3952132a08ae5764")
]},
{$gte: [
"$$this.date",
"$date"
]}
]}
]
}
}}
]
}
}}
])
这篇关于Mongodb如果然后在过滤条件下如何制作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文