I have the following Documents:
- A
User
document. - An embedded document, containing a reference to (see next document)
- a
Site
document
Each user has an array of embedded documents inside, each representing an item he follows - a site, a twitter account - with the option to mark specific categories he's interested in. Each embedded document has a reference to the third document - the Site
document (or Twitter
document, etc..).
The question is - using the MongoDB ODM, how can I get the documents of all the users that chose to follow a given site, using the id of that site ?
(see below (after the files) how it is done 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 user 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 command for getting all the users that are following a specific site:
db.User.find({"follows.siteItem": ObjectId("OBJECT_ID_OF_SITE_DOCUMENT")})
$builder->Field ('follows. siteItem')->getQuery()->execute();
– Orlena