- 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
MongoDB query to collectively match intersection of documents against a field
For this, use aggregate(). Let us first create a collection with documents −
> db.demo393.insertOne( ... { ... Id1: "1", ... Name: "Chris", ... Id2: "100" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e6dd522064be7ab44e804") } > db.demo393.insertOne( ... { ... Id1: "1", ... Name: "Chris", ... Id2: "101" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e6dd522064be7ab44e805") } > db.demo393.insertOne( ... { ... Id1: "3", ... Name: "Chris", ... Id2: "100" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e6dd522064be7ab44e806") } > db.demo393.insertOne( ... { ... Id1: "3", ... Name: "Mike", ... Id2: "101" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e6dd522064be7ab44e807") }
Display all documents from a collection with the help of find() method −
> db.demo393.find();
This will produce the following output −
{ "_id" : ObjectId("5e5e6dd522064be7ab44e804"), "Id1" : "1", "Name" : "Chris", "Id2" : "100" } { "_id" : ObjectId("5e5e6dd522064be7ab44e805"), "Id1" : "1", "Name" : "Chris", "Id2" : "101" } { "_id" : ObjectId("5e5e6dd522064be7ab44e806"), "Id1" : "3", "Name" : "Chris", "Id2" : "100" } { "_id" : ObjectId("5e5e6dd522064be7ab44e807"), "Id1" : "3", "Name" : "Mike", "Id2" : "101" }
Following is the query to collectively match intersection of documents against a field −
> db.demo393.aggregate([ ... { "$match": { "Name": "Chris" } }, ... { "$group": { ... "_id": "$Id1", ... "docs": { "$push": "$$ROOT" }, ... "count": { "$sum": 1 } ... }}, ... { "$match": { ... "count": { "$gt": 1 }, ... "docs": { ... "$all": [ ... { "$elemMatch": { "Id2": "100" } }, ... { "$elemMatch": { "Id2": "101" } } ... ] ... } ... }} ... ])
This will produce the following output −
{ "_id" : "1", "docs" : [ { "_id" : ObjectId("5e5e6dd522064be7ab44e804"), "Id1" : "1", "Name" : "Chris", "Id2" : "100" }, { "_id" : ObjectId("5e5e6dd522064be7ab44e805"), "Id1" : "1", "Name" : "Chris", "Id2" : "101" } ], "count" : 2 }
Advertisements