问题
I got stuck in one point. See this playground, it should follow this logic:
- if history's collection is empty, return data
- if history's date collection is greater then main's collection base on specified
user_id
, return nothing - if specified
user_id
doesn't match with history's collection date then it should return all data that is in main collection.
So everything looks fine in playground the only problem when i am putting 5e4e74eb380054797d9db623
id it should not return me data because its date is over then main collection
db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}
},
{
$unwind: {
path: "$History",
preserveNullAndEmptyArrays: true
}
},
{
$sort: {
_id: 1,
"History.history_id": 1,
"History.date": 1
}
},
{
$group: {
_id: "$_id",
data: {
$last: "$$ROOT"
},
History: {
$last: "$History"
}
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$data",
{
History: "$History"
}
]
}
}
},
{
"$match": {
$expr: {
$or: [
{
$eq: [
{
$type: "$History.date"
},
"missing"
]
},
{
$ne: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
},
{
$and: [
{
$eq: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
},
{
$gt: [
"$date",
"$History.date"
]
}
]
}
]
}
}
}
])
MongoPlayground
来源:https://stackoverflow.com/questions/61504061/mongodb-group-compare-one-collection-to-other-collection