使用聚合子查询作为过滤器将查询结果插入到新集合中

问题描述 投票:0回答:1

如何在 MongoDB 中实现这个查询

select * into NewTable 
from SalesInvoice where SalesID in 
   (select SalesID from SalesInvoice 
        group by CustomerID 
          having count(CustomerID)>1
    )

我可以构建聚合查询,但无法找到一种方法来进行新查询并使用聚合查询作为过滤器,然后将结果插入到新集合中。

以下为聚合查询:

db.SalesInvoice.aggregate([ {$group: {_id:"$request.CustomerID", count: {$sum:1}}},{$match: {count: {$gt:1}}}])
mongodb mongodb-query
1个回答
0
投票

认为有几种方法可以实现:

方法1

  1. $lookup
    - 通过
    CustomerID
    左连接自集合并返回 salesInvoices` 数组。

  2. $match
    - 使用
    salesInvoices
    数组大小大于1的文档进行过滤。

  3. $unset
    - 删除
    salesInvoices
    数组。

  4. out
    - 将结果导出到集合中。

db.SalesInvoice.aggregate([
  {
    $lookup: {
      from: "SalesInvoice",
      let: {
        custID: "$CustomerID"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$CustomerID",
                "$$custID"
              ]
            }
          }
        }
      ],
      as: "salesInvoices"
    }
  },
  {
    $match: {
      $expr: {
        $gt: [
          {
            $size: "$salesInvoices"
          },
          1
        ]
      }
    }
  },
  {
    $unset: "salesInvoices"
  },
  {
    $out: "<Your new collection>"
  }
])

演示方法 1 @ Mongo Playground


方法2

  1. $facet
    - 允许在单个查询中运行多个聚合管道。

    1.1。

    salesInvoices
    - 返回 salesInvoices 集合中的所有文档。

    1.2。

    filterCustomers
    - 获取
    salesInvoices
    集合中超过 1 个文档中出现的 CustomerID

  2. $unwind
    - 解构
    salesInvoices
    数组。

  3. $match
    - 通过匹配
    SalesInvoices.CustomerID
    来过滤文档。

  4. $replaceWith
    - 将输入文档替换为
    SalesInvoices
    字段。

  5. out
    - 将结果导出到集合中。

db.SalesInvoice.aggregate([
  {
    $facet: {
      salesInvoices: [],
      filteredCustomers: [
        {
          $group: {
            _id: "$CustomerID",
            count: {
              $sum: 1
            }
          }
        },
        {
          $match: {
            count: {
              $gt: 1
            }
          }
        },
        {
          $project: {
            _id: 1
          }
        }
      ]
    }
  },
  {
    $unwind: "$salesInvoices"
  },
  {
    $match: {
      $expr: {
        $in: [
          "$salesInvoices.CustomerID",
          "$filteredCustomers._id"
        ]
      }
    }
  },
  {
    $replaceWith: "$salesInvoices"
  },
  {
    $out: "<Your new collection>"
  }
])

演示方法 2 @ Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.