【问题标题】:PHP mongoDB distinct selectionPHP mongoDB 不同的选择
【发布时间】:2014-01-09 03:55:40
【问题描述】:

这是我第一次在 stackoverflow 上发帖。我希望有人可以帮助我解决 mongoDB PHP 的问题。我更像是一个 PHP mySql 人,但我们突然需要切换到 mongoDB。以下是我能给出的最多解释中的问题情况。

想象一下,在 mysql 中,我有一个名为“photos”的表,其中包含 3 个字段(img_id、owner_id 和 file_path)。并记录如下:

记录#1: 1---1---image01.jpg

记录#2: 2---2---image02.jpg

记录#3: 3---2---image03.jpg

然后我有另一个名为“users”的表,其中包含 2 个字段(user_id、fullname),记录如下:

记录 #1: 1---Jhon Doe

记录 #2: 2---马克凯恩

我只需要显示类似于以下的结果:

1.) John Doe1 图片,图片 ID 为 1。 -image01.jpg

2.) Mark Kane2 张图片,图片 ID 为 23。 -image01.jpg、image02.jpg

请让我知道这应该如何在 mongoDB PHP 中完成。提前致谢。

【问题讨论】:

    标签: php mongodb join distinct


    【解决方案1】:
    $m = new Mongo();
    $collection = $m->users;
    $collection1 = $m->photos;
    $cursor = $collection->find();
    $cursor1 = $collection1->find();
    
    $count = 0;
    $result = array();
    $path = array();
    $str = "";
    $str1 = "";
    foreach($cursor as $obj){
        foreach($cursor1 as $obj1){
            if($obj['user_id'] == $obj1['owner_id']){
                $result[$count] = $obj1['img_id'];
                $path[$count] = $obj1['file_path'];         
                $count++;
            } 
        }
        if($count > 1){
            for($i = 0; $i < $count; $i++){
                $str .= $result[$count]." and ";
                $str1 .= $path[$count]." , ";
            }       
        }
        else{   
            $str = $result[0];
            $str1 = $path[0];   
        }
        print "$obj['fullname'] has $count image and the image id is $str - $str1 .";
    }
    

    希望上面的代码块能给你想要的结果,代码没有经过测试,所以可能存在一些编译器或语法错误,但我希望你能解决它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 2015-09-09
      • 1970-01-01
      • 2020-10-14
      • 2012-09-10
      相关资源
      最近更新 更多