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
Set filtering conditions for nested array in MongoDB
To set filtering conditions, use $filter and $cond in MongoDB aggregate(). The $filter selects a subset of an array to return based on the specified condition. Let us create a collection with documents −
> db.demo725.insertOne(
... {
...
... "details": {
...
... "userMessages": [
... {
... "Messages": [
... { "Message": "Hello" },
... { "Message": "How" },
... { "Message": "are" }
... ]
...
... },
... {
... "Messages": [
... { "Message": "Good" },
... { "Message": "Bye" }
...
... ]
... },
... {
... "Messages": [
... { "Message": "Hello" },
... { "Message": "Bye" }
...
... ]
...
... }
... ]
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eab16cd43417811278f5893")
}
Display all documents from a collection with the help of find() method −
> db.demo725.find();
This will produce the following output −
{ "_id" : ObjectId("5eab16cd43417811278f5893"), "details" : { "userMessages" : [ { "Messages" : [ { "Message" : "Hello" }, { "Message" : "How" }, { "Message" : "are" } ] }, { "Messages" : [ { "Message" : "Good" }, { "Message" : "Bye" } ] }, { "Messages" : [ { "Message" : "Hello" }, { "Message" : "Bye" } ] } ] } }
Following is the query to set filtering conditions for nested array −
> db.demo725.aggregate([
... {
... $addFields: {
... "details.userMessages": {
... $filter: {
... input: "$details.userMessages",
... as: "out",
... cond: {
... $anyElementTrue: {
... $map: {
... input: "$$out.Messages",
... in: { $gte: [ { $indexOfBytes: [ "$$this.Message", "Hello" ] }, 0 ] }
... }
... }
... }
... }
... }
... }
... }
... ]).pretty()
This will produce the following output −
{
"_id" : ObjectId("5eab16cd43417811278f5893"),
"details" : {
"userMessages" : [
{
"Messages" : [
{
"Message" : "Hello"
},
{
"Message" : "How"
},
{
"Message" : "are"
}
]
},
{
"Messages" : [
{
"Message" : "Hello"
},
{
"Message" : "Bye"
}
]
}
]
}
}Advertisements