Is there a way to use the mongodb aggregation framework to find duplicates in document arrays?
Here is a simplified version of the box collection:
{_id : 1, name : 'Box 1', products : [
{pId : 123, name : 'sneaker'},
{pId : 456, name : 'pants'},
{pId : 789, name : 'shirt'}
]},
{_id : 2, name : 'Box 2', products : [
{pId : 123, name : 'sneaker'},
{pId : 456, name : 'pants'},
{pId : 111, name : 'socks'}
]},
{_id : 3, name : 'Box 3', products : [
{pId : 123, name : 'sneaker'},
{pId : 222, name : 'belt'},
{pId : 333, name : 'shorts'}
]}
Lets say I want to check if the box 1 products are part of any other boxes.
Can I use the aggregation framework like this:
box.aggregate([
{$match: {'products.pId' : {$in : [123, 456, 789]}},
// ?? //
]);
Ideally I am hoping for an output like this:
[{_id : 123, count : 3,
{_id : 456, count : 2,
{_id : 789, count : 1}]
I know this can be achieved by returning all docs and them looping over each products array but wanted to see if mongodb can export this directly.
Thanks!!
question from:
https://stackoverflow.com/questions/65852118/find-duplicates-in-mongo-db-array-across-multiple-documents 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…