> 文章列表 > mongodb $lookup 联表查询

mongodb $lookup 联表查询

mongodb $lookup 联表查询

ollection  orders :      orders   record example

collection  items :items record example 

$lookup 联表查询

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

db.orders.aggregate( [{$lookup: {from: \"items\",localField: \"item\",    // field in the orders collectionforeignField: \"item\",  // field in the items collectionas: \"fromItems\"}},{$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ \"$fromItems\", 0 ]