How can I implement this query in MongoDB
select * into NewTable
from SalesInvoice where SalesID in
(select SalesID from SalesInvoice
group by CustomerID
having count(CustomerID)>1
)
I could build the aggregate query, but couldn't find a way to make a new query and use the aggregate query as a filter and then insert the result into new collection.
Below is aggregate query:
db.SalesInvoice.aggregate([ {$group: {_id:"$request.CustomerID", count: {$sum:1}}},{$match: {count: {$gt:1}}}])
Think there are a few approaches to achieve:
Approach 1
$lookup- Left join with the self-collection byCustomerIDand return a salesInvoices` array.$match- Filter the document with the size of thesalesInvoicesarray with more than 1.$unset- Remove thesalesInvoicesarray.out- Export the result into the collection.Demo Approach 1 @ Mongo Playground
Approach 2
$facet- Allow multiple aggregation pipelines to be run in a single query.1.1.
salesInvoices- Return all documents from the salesInvoices collection.1.2.
filterCustomers- Get theCustomerIDthat appeared in more than 1 document in the salesInvoices collection.$unwind- Deconstruct thesalesInvoicesarray.$match- Filter the document by matchingSalesInvoices.CustomerID.$replaceWith- Replace the input document withSalesInvoicesfield.out- Export the result into the collection.Demo Approach 2 @ Mongo Playground