I have my data saved in mongo db like this
{
"_id": "5eff4376e036e45de9dbc6df",
"social_connections":{
"friend":{
"friends":[
{
"_id": "5eff42dee036e45de9dbc6d3",
"user_name": "x",
"name": "Viper King"
},
{
"_id": "5eff40efe036e45de9dbc6c9",
"user_name": "z",
"name": "Brad Prasad Pitt"
},
{
"_id": "5eff50337508da5ff40bf36e",
"user_name": "test",
"name": "Test"
}
]
},
"followers":{
"following":[
{
"_id": "5eff42dee036e45de9dbc6d3",
"user_name": "x",
"name": "Viper King"
},
{
"_id": "5eff40efe036e45de9dbc6c9",
"user_name": "z",
"name": "Brad Prasad Pitt"
},
{
"_id": "5eff50337508da5ff40bf36e",
"user_name": "test",
"name": "Test"
}
]
}
}
}
I want to make a mongo db query in which I would pass the _id of the document that is 5eff4376e036e45de9dbc6df and a regex that is 'Vi', now I want all those array objects whose name contains 'Vi'. My expected output is:-
{
"_id": "5eff4376e036e45de9dbc6df",
"social_connections":{
"friend":{
"friends":[
{
"_id": "5eff42dee036e45de9dbc6d3",
"user_name": "x",
"name": "Viper King"
}
]
},
"followers":{
"following":[
{
"_id": "5eff42dee036e45de9dbc6d3",
"user_name": "x",
"name": "Viper King"
}
]
}
}
}
You can also make a query which only return _id of those whose name contains 'Vi'
friendsandfollowing.friends? You need to user the aggregation pipe where you should first use the $unwind both the array objects and then regex match them and use$regexto match your string then user $project to get the required output.