
- MongoDB Tutorial
- MongoDB - Home
- MongoDB - Overview
- MongoDB - Advantages
- MongoDB - Environment
- MongoDB - Data Modeling
- MongoDB - Create Database
- MongoDB - Drop Database
- MongoDB - Create Collection
- MongoDB - Drop Collection
- MongoDB - Data Types
- MongoDB - Insert Document
- MongoDB - Query Document
- MongoDB - Update Document
- MongoDB - Delete Document
- MongoDB - Projection
- MongoDB - Limiting Records
- MongoDB - Sorting Records
- MongoDB - Indexing
- MongoDB - Aggregation
- MongoDB - Replication
- MongoDB - Sharding
- MongoDB - Create Backup
- MongoDB - Deployment
- MongoDB - Java
- MongoDB - PHP
- Advanced MongoDB
- MongoDB - Relationships
- MongoDB - Database References
- MongoDB - Covered Queries
- MongoDB - Analyzing Queries
- MongoDB - Atomic Operations
- MongoDB - Advanced Indexing
- MongoDB - Indexing Limitations
- MongoDB - ObjectId
- MongoDB - Map Reduce
- MongoDB - Text Search
- MongoDB - Regular Expression
- Working with Rockmongo
- MongoDB - GridFS
- MongoDB - Capped Collections
- Auto-Increment Sequence
- MongoDB Useful Resources
- MongoDB - Questions and Answers
- MongoDB - Quick Guide
- MongoDB - Useful Resources
- MongoDB - Discussion
How to get the 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 ] }
- Related Articles
- How to find the intersection of two arrays in java?
- How to get data of array intersection in MongoDB?
- Intersection of two arrays in Java
- Intersection of two arrays in C#
- Intersection of Two Arrays in C++
- Intersection of two arrays JavaScript
- How to find intersection between two Numpy arrays?
- Intersection of Two Arrays II in Python
- How to Create an Array using Intersection of two Arrays in JavaScript?
- Get the intersection of two sets in Java
- Find Union and Intersection of two unsorted arrays in C++
- C program to perform intersection operation on two arrays
- The intersection of two arrays in Python (Lambda expression and filter function )
- C++ program to find union and intersection of two unsorted arrays
- How to get only values in arrays with MongoDB aggregate?

Advertisements