Using Doctrine MongoDB ODM - How to find documents by fields of embedded documents?

I have the following documents:

  • A User .
  • The attached document containing the link (see the following document)
  • a Site document

Each user has an array of embedded documents inside, each of which represents the element that he follows - a site, a Twitter account, with the ability to mark categories of interest to them. Each embedded document has a link to a third document - a Site document (or Twitter document, etc.).

Question: using ODM MongoDB, how can I get documents of all users who decide to follow this site using the identifier of this site?
(see below (after files) how to do this in the mongodb shell)

User.php

 <?php use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** * @ODM\Document */ class User { /** * @ODM\Id * @var string */ protected $id; /** * @ODM\EmbedMany( * discriminatorMap={ * "site"="SiteFollow", * "twitter"="TwitterFollow", * } * ) * @var ArrayCollection; */ protected $follows; } 

SiteFollow.php

 <?php use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** * @ODM\EmbeddedDocument */ class SiteFollow { /** * @ODM\Collection * @var array */ protected $interestingCategories; /** * @ODM\ReferenceOne(targetDocument="Site", simple=true) * @var Site */ protected $siteItem; } 

Site.php

 <?php use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** * @ODM\Document */ class Site { /** * @ODM\Id * @var string */ protected $id; /** * @ODM\String * @var string */ protected $name; /** * @ODM\String * @var string */ protected $url; } 

An example for a custom document in the mongo shell:

 db.User.findOne() { "_id": ObjectId("123"), "follows": [ { "interestingCategories": [ "PHP" ] "siteItem" : ObjectId("OBJECT_ID_OF_SITE_DOCUMENT"), "_doctrine_class_name" : "site" } ] } 

Mongo shell to get all users following a specific site:

 db.User.find({"follows.siteItem": ObjectId("OBJECT_ID_OF_SITE_DOCUMENT")}) 
+4
source share
2 answers

I found that the answer provided by Madarco sometimes does not work properly. If you request the $id field of a referenced field in an embedded document, you may need to pass the MongoId object to the equals() method. Therefore, in this case it will be:

 $repo = $odm->getRepository('User'); $repo->createQueryBuilder() ->field('follows.siteItem.$id') ->equals(new \MongoId($siteId)) ->getQuery() ->execute(); 
+4
source

Just a request for the $ id field of the DbRef siteItem field in the siteItem document (which is in the built-in collection in the user document):

 $repo = $odm->getRepository("User"); $repo->createQueryBuilder()->field("follows.siteItem.$id")->equals($siteId)->getQuery()->execute(); 
+1
source

All Articles