Reputation: 39
I have this problem. I have this dataBase in mongoDB:
{
"_id" : ObjectId("585fe33d3c63b4a81e00002b"),
"class" : [
{
"name" : "class 1",
"people" : [
{
"id" : "58596",
"name" : "mark",
},
{
"id" : "45643",
"name" : "Susan",
},
{
"id" : "85952",
"name" : "Loris",
}
},
{
"name" : "class 2",
"people" : [
{
"id" : "58456",
"name" : "Sissi",
},
{
"id" : "45643",
"name" : "Susan",
}
]
}
]
}
I use php and I would like to know the names of the class with a specific name inside and save them in an array.
For example if I choose Susan i would like to have an array with ["class 1" , ["class 2"]
.
I have used findOne but this time i need to use find.
Upvotes: 0
Views: 34
Reputation: 576
You can make use of MongoDB aggregation framework.
Here is a query which will give you the date in the desired form. However, I believe that there will be some better and efficient way to handle this but this is what I came up with.
db.collection.aggregate([
{"$unwind":"$class"},
{"$unwind":"$class.people"},
{"$match": {
"class.people.name":"Susan"
}
},
{"$group":{
"_id":"$class.people.name",
"classes":{"$push":"$class.name"}
}
}
])
Result :-
{ "_id" : "Susan", "classes" : [ "class 1", "class 2" ] }
Try to $match
before first $unwind
operation to avoid the unnecessary results in the pipeline before $unwind
.
Refer Aggregation Pipeline Optimization for improved performance.
Upvotes: 1