I am having trouble in returning only the matched embedded document using MongoDB ODM query builder in PHP. Each embedded document has a MongoID generated at the time of creation. Following is my document structure of collection Project:
{
"_id" : ObjectId("59f889e46803fa3713454b5d"),
"projectName" : "usecase-updated",
"classes" : [
{
"_id" : ObjectId("59f9d7776803faea30b895dd"),
"className" : "OLA"
},
{
"_id" : ObjectId("59f9d8ad6803fa4012b895df"),
"className" : "HELP"
},
{
"_id" : ObjectId("59f9d9086803fa4112b895de"),
"className" : "DOC"
},
{
"_id" : ObjectId("59f9d9186803fa4212b895de"),
"className" : "INVOC"
}
]
}
Now i want to retrieve from the database only the class from the classes embedded documents which meets my criteria (i.e. class with a specific id).This is how i am building the query:
$qb = $dm->createQueryBuilder('Documents\Project');
$projectObj = $qb
->field('id')->equals("59f889e46803fa3713454b5d")
->field('classes')->elemMatch(
$qb->expr()->field("id")->equals(new \MongoId("59f9d7776803faea30b895dd"))
)
->hydrate(false)
->getQuery()
->getSingleResult();
First i match with the project id then i match with the embedded document class id. I was expecting it to return only the embedded document of OLA like this:
{
"_id" : ObjectId("59f889e46803fa3713454b5d"),
"projectName" : "usecase-updated",
"classes" : [
{
"_id" : ObjectId("59f9d7776803faea30b895dd"),
"className" : "OLA"
}
]
}
But doctrine is returning the whole Project record (shown in the start of question).I also tried with aggregation query building with the $match aggregation still the results are same the query i created with aggregation builder is as follows:
$qb = $dm->createAggregationBuilder('Documents\Project');
$projectObj = $qb
->match()
->field('id')->equals($projectId)
->field('classes._id')->equals(new \MongoId($classId))
->execute()
->getSingleResult();
Can someone help me with regards to this issue? How can i build query that i get the desired result as mentioned above.