Question

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?

Was it helpful?

Solution

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');

OTHER TIPS

You must use the references() method of Query Builder for a @MongoDB\ReferenceOne like https://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/query-builder-api.html

$productType = $dm->getRepository('Cms\Model\ProductTypes')->findOneByCode('car');

$queryBuilder = $dm->getRepository('Cms\Model\Param')->createQueryBuilder()
                   ->field('productTypes')->references($productType);

$results = $queryBuilder->getQuery()->execute();


PS: use includesReferenceTo() a @MongoDB\ReferenceMany

->field('productTypes.code')->equals(new \MongoRegex('/.*car.*/i'))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top