我有两个集合
集合A
[{id:1,name:A},{id:2,name:B},{id:3,name:C},{id:4,name:D},{id:5,name:E}]
集合B
[{aid:2,product:X,date:2009-11-09},{aid:4,product:Y,date:2009-11-09},{aid:3,product:Y,date:2009-11-08}]
我想创建一个聚合,它将返回A中所有在B中没有辅助的元素。
预期结果:
[{id:1,name:A},{id:3,name:C},{id:5,name:E}]
这就是我尝试的
CollectionB.aggregate([
{
$match: {date : {$gte: "2009-11-09T00:00:00.000Z" ,$lt: "2009-11-09T23:59:59.999Z"} }
},
{ $lookup: {
from: "CollectionA",
let: {
aid: "$aid"
},
pipeline: [
{ $match: {
$expr: {
$not: [ { $eq: [ "$$aid", "$id" ] } ]
}
} }
],
as: "result"
}
},
], function (err, result) {}
这只可能在应用层中实现吗?
TIA-
尝试以下聚合查询(不同之处在于可以聚合到CollectionA
而不是CollectionB
(:
db.getCollection('CollectionA').aggregate([
{
"$lookup": // Run a $lookup to join these two collections
{
"from": "CollectionB",
"localField": "id",
"foreignField": "aid",
"as": "combinedResults"
}
},
{
"$match" : {
"combinedResults" : [] // Filter the result for which the aid wasn't found
}
}
])
//Voila! Hope this helps!