Search This Blog

2024/04/24

MongoDb Interview Question:Filter Object Array

Problem:

Assume there is a collection named users that looks like the one below. How can
you get all houses in the “Rabia” neighborhood?

db.userHouses.insertMany([
{
"_id" : ObjectId("5d011c94ee66e13d34c7c388"),
"userName" : "kevin",
"email" : "kevin@toptal.com",
"password" : "affdsg342",
"houses" : [
{
"name" : "Big Villa",
"neighborhood" : "Zew Ine"
},
{
"name" : "Small Villa",
"neighborhood" : "Rabia"
}
]
},
{
"_id" : ObjectId("5d011c94ee66e13d34c7c387"),
"userName" : "sherif",
"email" : "sharief@toptal.com",
"password" : "67834783ujk",
"houses" : [
{
"name" : "New Mansion",
"neighborhood" : "Nasr City"
},
{
"name" : "Old Villa",
"neighborhood" : "Rabia"
}
]
},

])

Solution:

db.userHouses.find(
{"houses.neighborhood":"Rabia"},
{
"houses":{$elemMatch:{"neighborhood" : "Rabia"}},
"_id":0
}

)

or

db.userHouses.aggregate([
{ $match: { 'houses.neighborhood': 'Rabia' } },
{
$project: {
filteredHouses: { // This is just an alias
$filter: {
input: '$houses',
as: 'houseAlias',
cond: { $eq: ['$$houseAlias.neighborhood', 'Rabia'] }
}
},
_id: 0
}
}

])

No comments:

Post a Comment