溫馨提示×

MongoDB聚合管道查詢?nèi)绾芜M(jìn)行嵌套

小樊
82
2024-10-30 15:05:30
欄目: 云計(jì)算

在MongoDB中,你可以使用聚合管道(aggregation pipeline)進(jìn)行嵌套查詢。聚合管道是一系列的階段(stages),每個(gè)階段都會(huì)對數(shù)據(jù)進(jìn)行某種操作。要在MongoDB中進(jìn)行嵌套查詢,你可以使用$unwind、$group$project等階段來處理數(shù)據(jù)。

以下是一個(gè)簡單的例子,說明如何在MongoDB中使用聚合管道進(jìn)行嵌套查詢:

假設(shè)我們有一個(gè)名為orders的集合,其中包含以下文檔:

[
  {
    "_id": 1,
    "customer_id": 1,
    "items": [
      { "product_id": 1, "quantity": 2 },
      { "product_id": 2, "quantity": 1 }
    ]
  },
  {
    "_id": 2,
    "customer_id": 2,
    "items": [
      { "product_id": 1, "quantity": 1 },
      { "product_id": 3, "quantity": 2 }
    ]
  },
  {
    "_id": 3,
    "customer_id": 1,
    "items": [
      { "product_id": 2, "quantity": 3 },
      { "product_id": 4, "quantity": 1 }
    ]
  }
]

現(xiàn)在,我們想要查詢每個(gè)客戶的總消費(fèi)金額(每個(gè)產(chǎn)品的數(shù)量乘以其價(jià)格)。首先,我們需要知道每個(gè)產(chǎn)品的價(jià)格。假設(shè)我們有一個(gè)名為products的集合,其中包含以下文檔:

[
  { "_id": 1, "name": "Product A", "price": 10 },
  { "_id": 2, "name": "Product B", "price": 20 },
  { "_id": 3, "name": "Product C", "price": 30 },
  { "_id": 4, "name": "Product D", "price": 40 }
]

我們可以使用以下聚合管道查詢來計(jì)算每個(gè)客戶的總消費(fèi)金額:

db.orders.aggregate([
  {
    $lookup: {
      from: "products",
      localField: "items.product_id",
      foreignField: "_id",
      as: "product_info"
    }
  },
  {
    $unwind: "$items"
  },
  {
    $unwind: "$product_info"
  },
  {
    $addFields: {
      "total_amount": { $multiply: ["$items.quantity", "$product_info.price"] }
    }
  },
  {
    $group: {
      _id: "$customer_id",
      total_spent: { $sum: "$total_amount" },
      items: { $push: "$items" },
      product_info: { $push: "$product_info" }
    }
  },
  {
    $project: {
      _id: 0,
      customer_id: "$_id",
      total_spent: 1,
      items: 1,
      product_info: 1
    }
  }
])

這個(gè)查詢的步驟如下:

  1. 使用$lookup階段將orders集合與products集合連接起來,以便獲取每個(gè)產(chǎn)品的價(jià)格。
  2. 使用$unwind階段將items數(shù)組和product_info數(shù)組拆分成多個(gè)文檔。
  3. 使用$addFields階段計(jì)算每個(gè)訂單項(xiàng)的總金額(數(shù)量乘以價(jià)格)。
  4. 使用$group階段按客戶ID對文檔進(jìn)行分組,并計(jì)算每個(gè)客戶的總消費(fèi)金額。
  5. 使用$project階段重新格式化輸出結(jié)果。

查詢結(jié)果將如下所示:

[
  {
    "customer_id": 1,
    "total_spent": 160,
    "items": [
      { "product_id": 1, "quantity": 2 },
      { "product_id": 2, "quantity": 1 },
      { "product_id": 2, "quantity": 3 },
      { "product_id": 4, "quantity": 1 }
    ],
    "product_info": [
      { "_id": 1, "name": "Product A", "price": 10 },
      { "_id": 2, "name": "Product B", "price": 20 },
      { "_id": 4, "name": "Product D", "price": 40 }
    ]
  },
  {
    "customer_id": 2,
    "total_spent": 90,
    "items": [
      { "product_id": 1, "quantity": 1 },
      { "product_id": 3, "quantity": 2 }
    ],
    "product_info": [
      { "_id": 1, "name": "Product A", "price": 10 },
      { "_id": 3, "name": "Product C", "price": 30 }
    ]
  }
]

0