如何在 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}}}])
认为有几种方法可以实现:
方法1
$lookup
- 通过 CustomerID
左连接自集合并返回 salesInvoices` 数组。
$match
- 使用salesInvoices
数组大小大于1的文档进行过滤。
$unset
- 删除 salesInvoices
数组。
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>"
}
])
方法2
$facet
- 允许在单个查询中运行多个聚合管道。
1.1。
salesInvoices
- 返回 salesInvoices 集合中的所有文档。
1.2。
filterCustomers
- 获取 salesInvoices集合中超过 1 个文档中出现的
CustomerID
。
$unwind
- 解构 salesInvoices
数组。
$match
- 通过匹配 SalesInvoices.CustomerID
来过滤文档。
$replaceWith
- 将输入文档替换为 SalesInvoices
字段。
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>"
}
])