0

I have a document User that contains

/**
 * @MongoDB\ReferenceOne(targetDocument="Image")
 */
private $image;

and a document ImageCollection which embed documents called Image

/** 
 * @MongoDB\EmbedMany(targetDocument="Image") 
 */
private $images = array();

and my embed-document Image that contains some usual fields. This is how I try to do the reference (uploader is a reference to some user):

$rep = $this->dm->getRepository('Document\ImageCollection');
$qb = $rep->createQueryBuilder('Document\ImageCollection')->field('images.uploader.$id')->equals(new \MongoId($uploader->getId()));
$query = $qb->getQuery(); // get query
$result = $query->execute(); // do query
$arr = $result->toArray(); // get array
$item = array_shift($arr); // get first item of array

$newUser = new Documents\User();
$newUser->setName('Bob King');
$newUser->setImage($item->getImages()[0]);

the result will be something like the following. The problem is, I dont know why I $ref and $db are correct while $id is null?

{
    "_id": ObjectID("51c2c357fa463404041b55ce"),
    "name": "Bob King",
    "image": {
        "$ref": "Image",
        "$id": null,
        "$db": "db_users_and_images"
    }
}
Michael
  • 1,922
  • 1
  • 19
  • 17

1 Answers1

1

The problem is that you cannot reference an Embedded Document. You can only reference a Document. Careful reading of the Data Modeling Considerations in the MongoDB documentation reveals that you have to choose between embedding and referencing.

In general, use Embedded Documents when you only need to access the Embedded Document from it's master Document (one-way has-many relationship). If you need reference a Document from multiple places (it belongs to more than one document) or query the document by itself, use references. There are many questions related to the tradeoffs between referencing and embedding on SO, so here is one question with a very good answer.

Community
  • 1
  • 1
mattexx
  • 6,456
  • 3
  • 36
  • 47