- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get data of array intersection in MongoDB?
For array interection in MongoDB, use the $setIntersection in aggregate(). Let us create a collection with documents −
> db.demo625.insertOne( ... { ... Name: "John", ... Marks: [56,98,60] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9ab8e16c954c74be91e6aa") } > db.demo625.insertOne( ... { ... Name: "John", ... Marks: [110,56,72] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9ab8e26c954c74be91e6ab") } > db.demo625.insertOne( ... { ... Name: "Chris", ... Marks: [90,91] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9ab8e26c954c74be91e6ac") } > db.demo625.insertOne( ... { ... Name: "Robert", ... Marks: [60,75] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9ab8e26c954c74be91e6ad") }
Display all documents from a collection with the help of find() method −
> db.demo625.find();
This will produce the following output −
{ "_id" : ObjectId("5e9ab8e16c954c74be91e6aa"), "Name" : "John", "Marks" : [ 56, 98, 60 ] } { "_id" : ObjectId("5e9ab8e26c954c74be91e6ab"), "Name" : "John", "Marks" : [ 110, 56, 72 ] } { "_id" : ObjectId("5e9ab8e26c954c74be91e6ac"), "Name" : "Chris", "Marks" : [ 90, 91 ] } { "_id" : ObjectId("5e9ab8e26c954c74be91e6ad"), "Name" : "Robert", "Marks" : [ 60, 75 ] }
Following is the query to get data of array intersection in MongoDB −
> db.demo625.aggregate([ ... ... ... { "$project": { ... "Name": 1, ... "Marks": { ... "$setIntersection": [ "$Marks", [56,98,60] ] ... } ... }} ... ])
This will produce the following output −
{ "_id" : ObjectId("5e9ab8e16c954c74be91e6aa"), "Name" : "John", "Marks" : [ 56, 60, 98 ] } { "_id" : ObjectId("5e9ab8e26c954c74be91e6ab"), "Name" : "John", "Marks" : [ 56 ] } { "_id" : ObjectId("5e9ab8e26c954c74be91e6ac"), "Name" : "Chris", "Marks" : [ ] } { "_id" : ObjectId("5e9ab8e26c954c74be91e6ad"), "Name" : "Robert", "Marks" : [ 60 ] }
Advertisements