当前位置:   article > 正文

mongodb $lookup 联表查询_mongo lookup联合查询性能

mongo lookup联合查询性能

collection  orders :      orders   record example

collection  items :items record example 

$lookup 联表查询

通过item字段连接两个集合orders和items,然后使用 $replaceRoot 中的 $mergeObjects 合并成items和orders的连接文档

  1. db.orders.aggregate( [
  2. {
  3. $lookup: {
  4. from: "items",
  5. localField: "item", // field in the orders collection
  6. foreignField: "item", // field in the items collection
  7. as: "fromItems"
  8. }
  9. },
  10. {
  11. $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }
  12. },
  13. { $project: { fromItems: 0 } }
  14. ] )

 建立集合:orders和items

  1. db.orders.insertMany( [
  2. { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
  3. { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 }
  4. ] )
  1. db.items.insertMany( [
  2. { "_id" : 1, "item" : "almonds", description: "almond clusters", "instock" : 120 },
  3. { "_id" : 2, "item" : "bread", description: "raisin and nut bread", "instock" : 80 },
  4. { "_id" : 3, "item" : "pecans", description: "candied pecans", "instock" : 60 }
  5. ] )

  查询结果为items和orders集合的合并文档:

  1. {
  2. _id: 1,
  3. item: 'almonds',
  4. description: 'almond clusters',
  5. instock: 120,
  6. price: 12,
  7. quantity: 2
  8. },
  9. {
  10. _id: 2,
  11. item: 'pecans',
  12. description: 'candied pecans',
  13. instock: 60,
  14. price: 20,
  15. quantity: 1
  16. }

gpt示例

代码中,$project操作符通过指定1或0来选择要包含或排除的字段,这里我们只选择了product_id字段,而将_id字段排除。

注意,由于只选择了product_id字段,查询结果中不会包含其他字段,例如订单编号、订单日期等等,这些字段如果需要在查询结果中显示,需要在$project操作符中添加相应的字段。

  1. db.orders.aggregate([
  2. {
  3. $lookup: {
  4. from: "items",
  5. localField: "product_id",
  6. foreignField: "product_id",
  7. as: "order_items"
  8. }
  9. },
  10. {
  11. $match: {
  12. "order_items": { $ne: [] }
  13. }
  14. },
  15. {
  16. $project: {
  17. _id: 0,
  18. product_id: 1
  19. }
  20. }
  21. ])

关联查询的实际操作:

  1. // 关联查询
  2. db.中国裁判文书网法院文书.aggregate([
  3. {
  4. $lookup: {
  5. from: "中国裁判文书网", // 要关联查询的集合
  6. localField: "7", // goods集合中的_id
  7. foreignField: "s7", // 要查询的集合的 关联id
  8. as: "anhao"
  9. }
  10. },
  11. {
  12. $match: {
  13. anhao: {$ne:[ ]} //查询条件,相当于where2021)豫1302民初9080
  14. }
  15. },
  16. {
  17. $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$anhao", 0 ] }, "$$ROOT" ] } }
  18. },
  19. { $project: { _id:0,"s7": 1,"s1":1} }
  20. ])

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/56015
推荐阅读
相关标签
  

闽ICP备14008679号