dougai2427
2016-12-28 16:49
浏览 64

如何在php中检索MongoDB多个数组值?

I want to retrieve all the values of the field color. How do php handle this values?

{
    _id : 1,

    color : ["red","blue","yellow"]
},
{
    _id : 2,

    color : ["green","black","grey"]
}

PHP code :

<?php

    $connect = new MongoClient();

    $collection = $database->database_name->collection;

    $cursor = $collection->find( array(), array( 'color' ) );

    foreach( $cursor as $val )

     echo json_encode( $val );

?>

As a result it does not return any values. How do I get the array values?

图片转代码服务由CSDN问答提供 功能建议

我想检索字段颜色的所有值。 php如何处理这个值?

  {
 _id:1,
 
 color:[“red”,“blue”,“yellow”] 
},
 {
 _id  :2,
 
颜色:[“绿色”,“黑色”,“灰色”] 
} 
   
 
 

PHP代码:

 &lt;?php 
 
 $ connect = new MongoClient(); 
 
 $ collection = $ database-&gt; database_name-&gt; collection;  
 
 $ cursor = $ collection-&gt; find(array(),array('color')); 
 
 foreach($ cursor as $ val)
 
 echo json_encode($ val); \  n 
?&gt; 
   
 
 

因此,它不会返回任何值。 如何获取数组值?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dougua9328 2016-12-28 18:45
    已采纳

    Use distinct to get distinct values of your array :

    $cursor = $collection->distinct('color');
    

    A full example :

    <?php
    
        $m = new MongoClient();
        $db = $m->selectDB("testDB");
        $cursor = $db->users->distinct('color');
        var_dump($cursor);
    
    ?>
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题