php mongodb $查询DB中的多个键无法正常工作

问题描述 投票:0回答:4

我有一个问题,当我使用来自mongoDB的值时查询无法工作但在我尝试静态/硬编码值时有效。你能指出我做得不对吗?

当我硬编码如下所示的值时,代码工作正常。

$customer = $this->mongo->selectCollection('bookings');
$cursor = $customer->find(array('provider_id' => "0", 'cat_id' => array('$in' => array('591d380c227951b706e18a56','591da979227951a10f004ad7','591d42292279517209004ad7'))));

但是当值来自mongoDB时,此查询无法正常工作。

$cattype = array();
foreach ($catlist  as $key => $value){ $cattype[] = "'".$value['cid']."'";}
$catlist = implode(',', $cattype);
$customer = $this->mongo->selectCollection('bookings');
$cursor = $customer->find(array('provider_id' => "0", 'cat_id' => array('$in' => array($catlist))));

$catlist = comes from mongoDB

提前致谢

php mongodb
4个回答
0
投票

有两个错误:

第一个是你的每一个。您可以添加'...',而不是添加ID。

foreach ($catlist  as $key => $value){
    $cattype[] = $value['cid']
}

第二个是在你的陈述中。你想传递$cattype数组,但$cattype已经是一个数组,所以你再次将它包装在一个数组中。

$cursor = $customer->find([
    'provider_id' => "0",
    'cat_id' => ['$in' => $catlist]
]);

0
投票

请使用首先需要转换为mongo id,它可以帮助你。

$cattype = array();
foreach ($catlist  as $key => $value) { 
  $cattype[] = new \MongoId($value['cid']);
}
$catlist = implode(',', $cattype);
$customer = $this->mongo->selectCollection('bookings');
$cursor = $customer->find(array('provider_id' => "0", 'cat_id' => 
array('$in' => array($catlist))));

0
投票
$cattype = array();
foreach ($catlist  as $key => $value) { 
   $cattype[] = $value['cid'];
}
$catlist = implode(',', $cattype);
$customer = $this->mongo->selectCollection('bookings');
$cursor = $customer->find(array('provider_id' => "0", 'cat_id' => 
      array('$in' => $catlist))
);

0
投票

我找到了答案。无需破坏$ cattype。只需将$ cattype直接放在$ in array中('$ in'=> array($ cattype))

© www.soinside.com 2019 - 2024. All rights reserved.