dougou5844 2016-01-30 02:06
浏览 50
已采纳

PHP / MongoDB查询帮助

I have a mongodb collection with multiple documents. I want to search all the documents, and return each documents instance of a record for 'foo'

Example Collection:

Object 1:
[_id] => MongoId Object (
    [$id] => 551993579285313235ebd120
)
[snaps] => Array (
    [0] => ["84062","3","","0-250000","1"]
    [1] => ["84062","4","","0-350000","1"]
)
[zip] => 84057

Object 2:
[_id] => MongoId Object (
    [$id] => 55198dfc928531ea36ebd11f
)
[zip] => testz

Object 3:
[_id] => MongoId Object (
    [$id] => 56a1594e9285319a0a22e15c
)
[snaps] => Array (
    [0] => ["84057","3","","0-250000","1"]
    [1] => ["84020","4","","0-350000","1"]
)
[zip] => 84062

I want to return object 1, and 3, but only the "snaps" records, and their values

Current code:

try {
                    $conn = new Mongo('localhost');
                    $db = $conn->remo_db1;
                    $c = $db->eudata;
                    $cursor = $c->find(array('snaps'));
                    foreach($cursor as $obj) {
                        echo $obj['snaps'];
                    }

                // disconnect from server
                $conn->close();
                }  catch (MongoConnectionException $e) {
                    die('Error connecting to MongoDB server');
                } catch (MongoException $e) {
                    die('Error: ' . $e->getMessage());
                }
  • 写回答

2条回答 默认 最新

  • douzong3599 2016-01-30 02:55
    关注

    The following will return all objects in the collection with non-empty 'snaps' records and their values:

    $cursor = $c->find( array('snaps'=>array('$nin' => array(' ','',null))), array('snaps'=>true));

    The first parameter is the query. It returns all objects in the collection that contain non-empty 'snaps' values.

    The second parameter makes it so only the 'snaps' field gets returned. (If you want to return all the fields, simply remove the second parameter).

    Hope it helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)