【问题标题】:Limit returned fields with PHP MongoClient find() query使用 PHP MongoClient find() 查询限制返回的字段
【发布时间】: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() 查询的返回字段限制为整个集合中每个文档的一个子文档。

【问题讨论】:

标签: php mongodb mongodb-query mongodb-php


【解决方案1】:

看起来我已经找到了解决方案...我会解决这个问题并保留它,以防它最终对其他人有用。

我最终要做的是更改我的 MongoClient 自定义类 find() 函数,该函数调用 $collection->find() 查询,以包含一个 $fields 参数。

现在,MongoClient->find() 查询如下所示:

$collection->find(
    array("vcs.type" => "git"),
    array("vcs" => 1, "app_name" = 1)
)

在 MongoClient::cursor::find() 上找到答案:here

【讨论】:

  • 嗯,发送数组不起作用?我经常使用这种方法。返回的错误是什么?
  • 好吧,我基本上尝试过这样做,但是 find() 函数的 query 部分使用了一个空 array()。由于我的类函数的工作方式,它不起作用......所以实际上,我正确使用了 mongoclient find() 查询,但我滥用了自己的代码。哦!
  • @deusofnull 我想你可以试试$cursor = $collection->find(); $cursor->limit(1); 据我记得我们在某个地方使用过这个。
  • @divaka 不限制投影
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多