温馨提示×

mongodb多表联合查询怎么实现

小亿
140
2023-11-18 13:45:16
栏目: 云计算

在MongoDB中,常用的实现多表联合查询的方法有两种:嵌套查询和引用字段。

  1. 嵌套查询(Embedding): 在一个集合中嵌套另一个集合的文档。通过嵌套查询,可以将相关联的数据放在同一个文档中,从而实现多表联合查询的效果。

    示例代码:

    // 创建一个用户集合
    db.users.insertMany([
      { _id: "1", name: "Tom", age: 20, address: "ABC Street" },
      { _id: "2", name: "John", age: 25, address: "XYZ Street" },
      // ...
    ])
    
    // 创建一个订单集合
    db.orders.insertMany([
      { _id: "1", userId: "1", products: ["product1", "product2"], amount: 100 },
      { _id: "2", userId: "2", products: ["product3"], amount: 50 },
      // ...
    ])
    
    // 查询用户及其订单
    db.users.aggregate([
      {
        $lookup: {
          from: "orders",
          localField: "_id",
          foreignField: "userId",
          as: "orders"
        }
      }
    ])
    
  2. 引用字段(Referencing): 在一个集合中使用外键引用另一个集合的文档。通过在一个集合中添加一个字段来引用另一个集合的文档,然后通过该字段进行关联查询。

    示例代码:

    // 创建一个用户集合
    db.users.insertMany([
      { _id: "1", name: "Tom", age: 20, address: "ABC Street" },
      { _id: "2", name: "John", age: 25, address: "XYZ Street" },
      // ...
    ])
    
    // 创建一个订单集合
    db.orders.insertMany([
      { _id: "1", userId: "1", products: ["product1", "product2"], amount: 100 },
      { _id: "2", userId: "2", products: ["product3"], amount: 50 },
      // ...
    ])
    
    // 查询用户及其订单
    db.users.aggregate([
      {
        $lookup: {
          from: "orders",
          localField: "_id",
          foreignField: "userId",
          as: "orders"
        }
      }
    ])
    

以上两种方法各有优缺点,具体使用哪种方法取决于数据的特点和查询的需求。

0