我的“params”集合中有一个文档,如下所示:
{
"_id": ObjectId("4d124cef3ffcf6f410000037"),
"code": "color",
"productTypes": [
{
"$ref": "productTypes",
"$id": ObjectId("4d120a2d2b8d8d3010000000"),
"$db": "test"
}
]
}
引用文件是这样的:
{
"_id": ObjectId("4d120a2d2b8d8d3010000000"),
"code": "car"
}
我正在使用 DoctrineODM 来获取引用“productType”为“car”的“param”文档。我正在使用此代码:
$query = $dm->createQuery('Cms\Model\Param');
$query->field('productTypes.code')->equals('car');
$result = $query->execute();
var_dump($result);
但结果是一个空数组。我该怎么做?
最佳答案
如果您使用 ReferenceMany 或 ReferenceOne,则不能通过任何引用文档字段查询,引用文档 ID 除外。
如果您需要从引用的集合中查询 code
,您应该使用 EmbedMany
而不是 ReferenceMany
。
在这种情况下,您的文档将是:
{
"_id": ObjectId("4d124cef3ffcf6f410000037"),
"code": "color",
"productTypes": [
{
"_id": ObjectId("4d120a2d2b8d8d3010000000"),
"code": "car"
}
]
}
以下查询将起作用:
$query = $dm->createQuery('Cms\Model\Param');
$query->field('productTypes.code')->equals('car');
$result = $query->execute();
var_dump($result);
此外,如果您的 ProductType 代码是唯一的,您可以使用它来代替 MongoId
,在这种情况下,您可以在 $id 上查询:
{
"_id": ObjectId("4d124cef3ffcf6f410000037"),
"code": "color",
"productTypes": [
{
"$ref": "productTypes",
"$id": 'car',
"$db": "test"
}
]
}
引用文献:
{
"_id": 'car'
}
查询:
$query->field('productTypes.$id')->equals('car');
关于mongodb - 如何通过 Doctrine ODM with MongoDB 中的引用文档查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4513872/