Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to aggregate two lists if at least one element matches in MongoDB?
To aggregate two lists if at least one element matches in MongoDB, use the aggregation pipeline with $unwind, $group, and $addToSet operators to identify common elements between arrays and group documents accordingly.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $group: { _id: "$arrayField", documentIds: { $addToSet: "$_id" }, count: { $sum: 1 } } },
{ $match: { count: { $gt: 1 } } },
// Additional pipeline stages to format results
]);
Sample Data
db.demo456.insertMany([
{ _id: 101, StudentName: ["Chris", "David"] },
{ _id: 102, StudentName: ["Mike", "Sam"] },
{ _id: 103, StudentName: ["John", "Jace"] },
{ _id: 104, StudentName: ["Robert", "John"] }
]);
{ "acknowledged" : true, "insertedIds" : { "0" : 101, "1" : 102, "2" : 103, "3" : 104 } }
Verify Sample Data
db.demo456.find();
{ "_id" : 101, "StudentName" : [ "Chris", "David" ] }
{ "_id" : 102, "StudentName" : [ "Mike", "Sam" ] }
{ "_id" : 103, "StudentName" : [ "John", "Jace" ] }
{ "_id" : 104, "StudentName" : [ "Robert", "John" ] }
Example: Find Documents with Matching Elements
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 } } }
]);
{ "_id" : "John", "combineIds" : [ 103, 104 ], "size" : 2 }
How It Works
- $unwind − Deconstructs the StudentName array into separate documents
- $group − Groups by student name and collects document IDs using $addToSet
- $match − Filters for names that appear in multiple documents (size > 1)
- The remaining stages reorganize the data to show which document IDs share common elements
Conclusion
Use MongoDB's aggregation pipeline with $unwind and $group operators to identify documents that share at least one common array element. The pipeline efficiently groups documents by matching array values and returns the aggregated results.
Advertisements
