0

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 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

6 Comments

So if I run this, I get "ArrayArray"... what is the correct way to echo this??
foreach($cursor as $obj) { print_r($obj); }
foreach($cursor as $obj) { var_dump($obj); }
Okay, I thought that was the case. I can open a new question if you want me to, but if I want to utilize the JSON arrays attached to each snaps value, how would I do this? I changed $obj to $obj['snaps'], but I am unsure where to proceed.
Okay. So I did: foreach ($obj['snaps'] as $snap){ echo $snap . PHP_EOL; } and now I can see all the JSON arrays in a line. If I wanted to choose JSON array 2, or 3, etc, how would I specify that?
|
0

Here is a guide on how to implement any mongoDb query in php:

http://php.net/manual/en/mongo.sqltomongo.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.