Mongodb

Mongodb find() 沒有按預期工作,PHP

  • March 13, 2019

Mongodb find() 似乎不起作用,我已經盡我所能,到目前為止沒有任何效果。使用 PHP7+

我在結構中有一個文件,如下圖所示

在此處輸入圖像描述

在 SQL 中,我可以執行以下操作:SELECT....... where 'common' LIKE '%Burk%'

簡單的查詢是呼叫國家集合和生產Burkina Faso作為輸出

問題 1:

$countries_tb= $db->selectCollection('country_city_data');
$countries = $countries_tb->find([],[
   'common' => new MongoDB\BSON\Regex('Burk')]);
var_dump($countries);

var_dump列印數據庫中所有國家的列表,而不是只獲取Burkina Faso

問題 2:

當我這樣做時find(without the empty [])var_dumps沒有必要

$countries = $countries_tb->find(/*without the []*/ [
   'common' => new MongoDB\BSON\Regex('Burk')]);

var_dump($countries);

我明白了:

在此處輸入圖像描述

我也試過這種格式。

問題 3:

$countries = $countries_tb->find(
                    array('name'=>
array(  'common'=>new MongoDB\BSON\Regex('Burk'))));

               var_dump($countries);

仍然沒有成功。

正如下面的@noobProgrammerSO 所建議的那樣,這樣做:

$countries_tb->find(['name' => 
                 ['common'=>new MongoDB\BSON\Regex('Burk')]], 
                 ['typeMap' => ['root' => 'array', 'document' => 'array']]);

產生這個;

在此處輸入圖像描述

我終於讓它工作了!

這就是我所做的。

$countries = $countries_tb->find(array('name.common' =>   array('$regex' =>  'Burk') ) );

注意.name.common

這是我的foreach循環'

foreach( $countries as $country => $name) { 

  foreach ($name as $n){

      if(isset($n->common)){

           var_dump($n->common);

       }

  }
}

//It prints out:    country_cities.php:90:string 'Burkina Faso' (length=12)

不知何故,這不起作用

$countries = $countries_tb->find(
                        array('name'=>
                                array('common' =>   
                                        array('$regex' =>   'Burk')) ) );

這是 JSON'

{"_id":"55a0f42f20a4d760b5fc306d","altSpellings":["BF"],"area":272967,"borders":["BEN","CIV","GHA","MLI","NER","TGO"],"callingCode":["226"],"capital":"Ouagadougou","cca2":"BF","cca3":"BFA","ccn3":"854","cioc":"BUR","currency":["XOF"],"demonym":"Burkinabe","landlocked":true,"languages":{"fra":"French"},"latlng":[13,-2],"name":{"common":"Burkina Faso","native":{"fra":{"common":"Burkina Faso","official":"Burkina Faso"}},"official":"Burkina Faso"},"region":"Africa","subregion":"Western Africa","tld":[".bf"],"translations":{"cym":{"common":"Burkina Faso","official":"Burkina Faso"},"deu":{"common":"Burkina Faso","official":"Burkina Faso"},"fin":{"common":"Burkina Faso","official":"Burkina Faso"},"fra":{"common":"Burkina Faso","official":"Burkina Faso"},"hrv":{"common":"Burkina Faso","official":"Burkina Faso"},"ita":{"common":"Burkina Faso","official":"Burkina Faso"},"jpn":{"common":"ブルキナファソ","official":"ブルキナファソ"},"nld":{"common":"Burkina Faso","official":"Burkina Faso"},"por":{"common":"Burkina Faso","official":"Burkina Faso"},"rus":{"common":"Буркина-Фасо","official":"Буркина -Фасо"},"spa":{"common":"Burkina Faso","official":"Burkina Faso"}}}

引用自:https://dba.stackexchange.com/questions/231840