How to aggregate two lists if at least one element matches in MongoDB?


For this, use $group in MongoDB. Within that, use $unwind, $group, $addToSet, etc. Let us create a collection with documents −

> db.demo456.insertOne(
... { _id: 101, StudentName: ["Chris", "David"] }
... );
{ "acknowledged" : true, "insertedId" : 101 }
>
> db.demo456.insertOne(
... { _id: 102, StudentName: ["Mike", "Sam"] }
... );
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo456.insertOne(
... { _id: 103, StudentName: ["John", "Jace"] }
... );
{ "acknowledged" : true, "insertedId" : 103 }
> db.demo456.insertOne(
... { _id: 104, StudentName: ["Robert", "John"] }
... );
{ "acknowledged" : true, "insertedId" : 104 }

Display all documents from a collection with the help of find() method −

> db.demo456.find();

This will produce the following output −

{ "_id" : 101, "StudentName" : [ "Chris", "David" ] }
{ "_id" : 102, "StudentName" : [ "Mike", "Sam" ] }
{ "_id" : 103, "StudentName" : [ "John", "Jace" ] }
{ "_id" : 104, "StudentName" : [ "Robert", "John" ] }

Following is the query to aggregate two lists if at least one element matches −

> db.demo456.aggregate([
... {$unwind:"$StudentName"},
... {$group:{_id:"$StudentName", combine:{$addToSet:"$_id"}, size:{$sum:1}}},
... {$match:{size: {$gt: 1}}},
... {$project:{_id: 1, combine:1, size: 1, combine1: "$combine"}},
... {$unwind:"$combine"},
... {$unwind:"$combine1"},
... {$group:{_id:"$combine", l:{$first:"$_id"}, size:{$sum: 1}, set: {$addToSet:"$combine1"}}},
... {$sort:{size:1}},
... {$group:{_id: "$l", combineIds:{$last:"$set"}, size:{$sum:1}}},
... {$match: {size:{$gt:1}}}
... ])

This will produce the following output −

{ "_id" : "John", "combineIds" : [ 103, 104 ], "size" : 2 }

Updated on: 11-May-2020

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements