How to find by referenced document in Doctrine ODM with MongoDB?

cnkt picture cnkt · Dec 22, 2010 · Viewed 11.1k times · Source

I have one document in my "params" collection like this:

{
  "_id": ObjectId("4d124cef3ffcf6f410000037"),
  "code": "color",
  "productTypes": [
    {
      "$ref": "productTypes",
      "$id": ObjectId("4d120a2d2b8d8d3010000000"),
      "$db": "test"
    }
  ]
}

the referenced document is this:

{
  "_id": ObjectId("4d120a2d2b8d8d3010000000"),
  "code": "car"
}

I'm using DoctrineODM to fetch the "param" documents which referenced "productType" is "car". I'm using this code:

$query = $dm->createQuery('Cms\Model\Param');
$query->field('productTypes.code')->equals('car');
$result = $query->execute();
var_dump($result);

but the result is an empty array. How can i do this?

Answer

Andrew Orsich picture Andrew Orsich · Jun 1, 2011

If you using ReferenceMany or ReferenceOne you can't query by any reference document field, except reference document id.

If you need query on code from referenced collection you should use EmbedMany instead of ReferenceMany.

In this case your document will be:

{
  "_id": ObjectId("4d124cef3ffcf6f410000037"),
  "code": "color",
  "productTypes": [
     {
       "_id": ObjectId("4d120a2d2b8d8d3010000000"),
       "code": "car"
     }
  ]
}

And following query will work:

$query = $dm->createQuery('Cms\Model\Param');
$query->field('productTypes.code')->equals('car');
$result = $query->execute();
var_dump($result);

Also if your ProductType code is unique you can use it instead of MongoId, in this case you can query on $id:

{
  "_id": ObjectId("4d124cef3ffcf6f410000037"),
  "code": "color",
  "productTypes": [
    {
      "$ref": "productTypes",
      "$id": 'car',
      "$db": "test"
    }
  ]
}

Referenced document:

{
  "_id": 'car'
}

Query:

$query->field('productTypes.$id')->equals('car');