Aggregation Pipeline实战实现inner join:
leftT集合:
comments集合:
现在我们要用aggregation实现inner join
db.comments.aggregate([{ $lookup: { from:"leftT", localField:"timestamp", foreignField:"timestamp", as: "timestampCol" }}, {$unwind: "$timestampCol"}, {$project: {"ratingEQ": {"$eq": ["$rating", "$timestampCol.rating"]}, "timestamp" : 1, "rating" : 1, "timestampCol.timestamp": 1}}, {$match: {"ratingEQ":true}} ])
是不是很神奇?
步骤解析:
- $lookup:实现timestamp的等值连接,相等的leftT结果被放在timestampCol集合中
- $unwind:实现把leftT数组拉平,出现多条
- $project:实现对第二个等值连接rating的判断,并放在ratingEQ字段中
- $match:只取ratingEQ是true,说明第二个rating字段相等