当前位置:  首页>> 技术小册>> MongoDB面试指南

答案:

要计算两个集合之间的交集,需要使用MongoDB的聚合框架。下面是实现这个问题的一些步骤:

使用$lookup操作符将两个集合连接起来。

  1. db.collection1.aggregate([
  2. {
  3. $lookup:
  4. {
  5. from: "collection2",
  6. localField: "_id",
  7. foreignField: "_id",
  8. as: "result"
  9. }
  10. }
  11. ])

使用$unwind操作符将连接的结果展开成单个文档。

  1. db.collection1.aggregate([
  2. {
  3. $lookup:
  4. {
  5. from: "collection2",
  6. localField: "_id",
  7. foreignField: "_id",
  8. as: "result"
  9. }
  10. },
  11. {
  12. $unwind: "$result"
  13. }
  14. ])

使用$match操作符将只包含匹配文档的结果过滤出来。

  1. db.collection1.aggregate([
  2. {
  3. $lookup:
  4. {
  5. from: "collection2",
  6. localField: "_id",
  7. foreignField: "_id",
  8. as: "result"
  9. }
  10. },
  11. {
  12. $unwind: "$result"
  13. },
  14. {
  15. $match: { "result": { $exists: true } }
  16. }
  17. ])

使用$project操作符仅返回需要的字段。

  1. db.collection1.aggregate([
  2. {
  3. $lookup:
  4. {
  5. from: "collection2",
  6. localField: "_id",
  7. foreignField: "_id",
  8. as: "result"
  9. }
  10. },
  11. {
  12. $unwind: "$result"
  13. },
  14. {
  15. $match: { "result": { $exists: true } }
  16. },
  17. {
  18. $project: { "_id": 1, "field1": 1, "field2": 1 }
  19. }
  20. ])

上述聚合管道将集合1和集合2中的文档连接起来,然后使用$unwind和$match操作符过滤出交集。最后,使用$project操作符返回所需字段。


该分类下的相关小册推荐: