简体   繁体   English

php:将mongodb嵌入式文档查询到数组中

[英]php: query mongodb embedded documents into an array

I have a database that I need to query and I need to get all of the results from an embedded document into an array so I can store them into variables in php. 我有一个数据库需要查询,我需要将所有结果从嵌入式文档中获取到数组中,以便将它们存储到php中的变量中。 This is what a record of the mongodb looks like: 这是mongodb的记录如下:

{
        "_id" : ObjectId("987654321"),
        "roles" : {
               "988434fe-9ac8-390f-abb4-18e4a0cc83fd" : 9,
               "fc261c0f-7124-3c81-89e8-ecb33771fe4e" : 9
        },
        "groupType" : "PUBLIC_GROUP",
        "name" : "Service Tech Role",
        "type" : "usergroup"
}

I can use the PHP function below to get all of the information from this document except for the embedded document data. 我可以使用下面的PHP函数从该文档中获取所有信息,嵌入式文档数据除外。

function getPerms()
  {
    $m = new MongoClient ("mongodb://localhost" );
    $db = $m->test;
    $collection = $db->roles;
    $query = array( '_id' => $_SESSION['groupId'] );
    $cursor = $collection->find( $query );
    foreach ($cursor as $document) {
      $_SESSION['object_permissions'] = $document["roles"];
    }
  }

What I need is for the "roles" data to be set in an array, like this: 我需要的是在数组中设置“角色”数据,如下所示:

988434fe-9ac8-390f-abb4-18e4a0cc83fd,9
fc261c0f-7124-3c81-89e8-ecb33771fe4e,9

What needs to be done to throw the embedded document into an array so I can store them as session variables in php? 需要执行什么操作才能将嵌入式文档放入数组中,以便将它们作为会话变量存储在php中?

I think your error lies elsewhere, it probably is more about the query returning zero documents, or the roles data being an empty array in the first place, or the roles data not existing and you having undefined index errors suppressed. 我认为您的错误在其他地方,它可能更多是与查询返回零文档有关,或者角色数据首先是空数组,或者角色数据不存在并且您有未定义的索引错误。

Can you prove that you can infact get all of the information from this document except for the embedded document data? 您能否证明可以从该文档中获取除嵌入式文档数据以外的所有信息? Do a var_dump($document) inside the loop. 在循环内执行var_dump($document)

I suspect your script is likely not even making it into the foreach loop. 我怀疑您的脚本可能甚至没有进入foreach循环。 You may need to check for mongodb query errors, or try modifying or removing the the query as a test. 您可能需要检查mongodb查询错误,或者尝试将查询修改或删除作为测试。

Side note: You should also be using findOne for this rather than find() 旁注:您还应该为此使用findOne而不是find()

$document = $collection->findOne($query);
$_SESSION['object_permissions'] = $document['roles'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM