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
Using $addFields pipeline and run with the MongoDB $filter operator
Let us first create a collection with documents −
> db.demo118.insertOne(
... {
... "Id" : "101",
... "Name" : "Chris",
... "Subjects" : [
... "MySQL",
... "MongoDB",
... "Java"
... ],
... "Details" : [
... {
... "Name" : "David",
... S:"MongoDB"
... },
... {
... "Name" : "Bob",
... S:"Python"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2f0c0cd8f64a552dae6364")
}
Display all documents from a collection with the help of find() method −
> db.demo118.find();
This will produce the following output −
{ "_id" : ObjectId("5e2f0c0cd8f64a552dae6364"), "Id" : "101", "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java" ], "Details" : [ { "Name" : "David", "S" : "MongoDB" }, { "Name" : "Bob", "S" : "Python" } ] }
Following is the query to use $addFields pipeline −
> db.demo118.aggregate([
... {
... "$addFields": {
... "Details": {
... "$filter": {
... "input": "$Details",
... "as": "out",
... "cond": { "$in": ["$$out.S", "$Subjects"] }
... }
... }
... }
... }
... ]).pretty();
This will produce the following output −
{
"_id" : ObjectId("5e2f0c0cd8f64a552dae6364"),
"Id" : "101",
"Name" : "Chris",
"Subjects" : [
"MySQL",
"MongoDB",
"Java"
],
"Details" : [
{
"Name" : "David",
"S" : "MongoDB"
}
]
}Advertisements