简体   繁体   English

如何在php中为mongoDB编写搜索查询?

[英]How to write search query in php for mongoDB?

this is my php script for inserting and retrieving data from mongoDB. 这是我的php脚本,用于从mongoDB插入和检索数据。 in the following the insertion works and find() method works too. 在下面的代码中,插入工作和find()方法也工作。 problem is when using condition inside find() method it won't give any results. 问题是当在find()方法中使用条件时,它不会给出任何结果。 why is that? 这是为什么?

//object class
class data{
    public $test1 = "default";
    public $test2 = "default";
}

//creating 4 objects and change some values and insert to DB
$data1 = new data();
$data1->test1 = '2';

$data2 = new data();
$data2->test1 = '2';

$data3 = new data();
$data3->test1 = '3';

$data4 = new data();

$collection->insert([$data1, $data2, $data3, $data4]);

//viewing all (this is works - retrieve all inserted data)
$res = $collection->find();

foreach($res as $val){
    var_dump($val);
}


//retrieve with condition (not works)
$q = array('test1' => '2');

$res2 = $collection->find($q);

foreach($res2 as $val2){
    var_dump($val2);
}

Because with this php script you insert only one object into Mongo. 因为使用此php脚本,您只能将一个对象插入Mongo。 http://php.net/manual/en/mongocollection.insert.php http://php.net/manual/en/mongocollection.insert.php

As a result in Mongo (you can check it with Mongo shell) you have something like this: 结果,在Mongo中(您可以使用Mongo Shell对其进行检查),您将得到以下内容:

{
"_id" : ...,
"0" : {
    "test1" : "2",
    "test2" : "default"
},
"1" : {
    "test1" : "2",
    "test2" : "default"
},
"2" : {
    "test1" : "3",
    "test2" : "default"
},
"3" : {
    "test1" : "default",
    "test2" : "default"
}

} }

From the code you can confirm it by using search condition: 从代码中,您可以使用搜索条件进行确认:

$q = array('0.test1' => '2');

To get desired result you should insert values like this: 为了获得理想的结果,您应该插入如下值:

$collection->insert($data1);
$collection->insert($data2);
$collection->insert($data3);
$collection->insert($data4);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM