
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Intersection of Two Arrays in MongoDB
To get intersection of two arrays, use $setIntersection along with aggregate(). Let us create a collection with documents −
> db.demo61.insertOne({"Values1":[10,20,30,40,50],"Values2":[30,100,70,120,40]}); { "acknowledged" : true, "insertedId" : ObjectId("5e286e28cfb11e5c34d8992a") }
Display all documents from a collection with the help of find() method −
> db.demo61.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e286e28cfb11e5c34d8992a"), "Values1" : [ 10, 20, 30, 40, 50 ], "Values2" : [ 30, 100, 70, 120, 40 ] }
Following is the query to get the intersection of two arrays in MongoDB −
> db.demo61.aggregate( ... [ ... { $project: { BothValues:{ $setIntersection: [ "$Values1", "$Values2" ] }} } ... ] ... );
This will produce the following output −
{ "_id" : ObjectId("5e286e28cfb11e5c34d8992a"), "BothValues" : [ 30, 40 ] }
Advertisements