【发布时间】:2015-02-16 16:02:39
【问题描述】:
我正在编写一个 PHP MongoClient 模型,该模型访问 mongodb,该模型存储带有 gitlab 信息、服务器主机和 zend 重启指令的部署日志。我有一个名为 deployAppConfigs 的 mongo 集合。它的文档结构如下所示:
{
"_id" : ObjectId("54de193790ded22d1cd24c36"),
"app_name" : "ai2_api",
"name" : "AI2 Admin API",
"app_directory" : "path_to_app",
"app_owner" : "www-data:deployers",
"directories" : [],
"vcs" : {
"type" : "git",
"name" : "input/ai2-api"
},
"environments" : {
"development" : {
...
},
"qa" : {
...
},
"staging" : {
...
},
"production" : {
...
},
"actions" : {
"post_checkout" : [
"composer_install"
]
}
}
因为这个集合中有很多文档,我想只查询整个集合的“vcs”子文档和“app_name”。我可以使用以下 find() 查询在 Robomongo 的 mongo shell 中执行此命令:
db.deployAppConfigs.find({}, {"vcs": 1, "app_name": 1})
这将准确返回集合中每个文档的我想要的内容:
{
"_id" : ObjectId("54de193790ded22d1cd24c36"),
"app_name" : "ai2_api",
"vcs" : {
"type" : "git",
"name" : "input/ai2-api"
}
}
我在编写与 mongo shell 命令等效的 PHP MongoClient 时遇到问题。我基本上想在Limit Fields to Return from a Query 上制作这个 mongo 文档示例的 PHP MongoClient 版本 我曾尝试使用空数组来替换 mongo shell 命令中的“{}”,但没有成功:
$query = array (
array(),
array("vcs"=> 1, "app_name"=> 1)
);
所有字段共享 vcs.type = "git" 所以我尝试编写一个查询,根据该共享值选择每个文档中的所有字段。它看起来像这样:
$query = array (
"vcs.type" => "git"
);
但这会返回整个文档,这是我想要避免的。
替代方法可能是对集合中的第一个文档执行限制投影 find(),然后使用 MongoCursor 遍历整个集合,但如果可能的话,我宁愿不必执行额外的循环。
本质上,我问的是如何将 find() 查询的返回字段限制为整个集合中每个文档的一个子文档。
【问题讨论】:
-
试试这样的:
db.deployAppConfigs.find({}, {"vcs": 1, "app_name": 1}).limit(5) -
是的,mongo 文档帮助我了解如何将查询输出限制为某些字段。我能够在 mongo shell 中做到这一点。对我来说,问题在于必须将其转换为 PHP MongoClient 代码。
-
这是 PHP stackoverflow.com/a/46988495/1191125 的正确答案 - 使用
projection
标签: php mongodb mongodb-query mongodb-php