新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

mongodb多表联合查询怎么实现,mongodb 连表

发布时间:2023-11-18 13:45:16

mongodb多表联合查询怎样实现

在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"
        }
      }
    ])
    

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