【问题标题】:Find all the documents in a collection using MongoManager class in PHP使用 PHP 中的 MongoManager 类查找集合中的所有文档
【发布时间】:2017-03-10 16:54:11
【问题描述】:

我想从Collection 中的所有文档中获取数据。在我的情况下,数据是Color 字段。我想从Collection 中的所有文档中检索所有Color 字段值。是否可以在PHP 中使用MongoManager 类?我正在尝试这种方式;

 $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $query = new MongoDB\Driver\Query([]);     
    $r = $mng->executeQuery("DB.Collection", $query);
    $R = current($r->toArray());

    if (!empty($R)) {
        echo ($R->Color);
    } else {
        echo "Nothing found";
    }

但它只给出一个字段。如何获取所有颜色字段?

【问题讨论】:

    标签: php mongodb mongodb-query


    【解决方案1】:

    您可以使用 distinct 从集合中获取 color 字段值。

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $cmd = new MongoDB\Driver\Command([
        'distinct' => Collection,
        'key' => 'color'
    ]);
    $cursor = $mng->executeCommand(DB, $cmd);
    $color = current($cursor->toArray())->values; 
    

    【讨论】:

    • 如果我想从所有文档中查找所有字段数据。不特定于color。然后?正如我的问题标题所说“查找集合中的所有文档”
    • 你只要做一个正常的查找来获取所有数据
    • 我的收藏有多个文档,每个文档都有颜色、链接、返回、提交、形状字段。我想要所有文档中的所有字段数据。
    • 类似$cursor = $mng ->executeQuery('DB.Collection', $query); foreach ($cursor as $document) { var_dump($document); }
    猜你喜欢
    • 2015-05-10
    • 2018-05-09
    • 2021-09-17
    • 2022-01-17
    • 1970-01-01
    • 2021-08-30
    • 2021-02-24
    • 2012-03-18
    • 2023-03-28
    相关资源
    最近更新 更多