0

I'm new to mongo. I'm working on a small site for managing a food storage database. When I query the database for key:value pairs I'm getting results but when I need to find sub values, e.g. key:{key:value}, I get nothing. Here is my record structure;

> db.foodstore.find().pretty()
{
        "_id" : ObjectId("5f5359676224333f529df761"),
        "shelf" : "1",
        "food" : "green beans",
        "container" : {
                "type" : "can",
                "size" : "#10"
        },
        "dateIn" : "09/20",
        "quantity" : "6"
}

Here is the php page code to query it:

<?php
require '../vendor/autoload.php';
$connection = new MongoDB\Client("mongodb://localhost:27017");
$collection = $connection->everything->foodstore;
echo "<div align='center'>";
$result = $collection->find([]);
echo "<table>";
foreach ($result as $entry){
        echo "<tr><td>",$entry['shelf'],
                "</td><td>",$entry['food'],
                "</td><td>",$entry['dateIn'],
                "</td><td>",$entry['container.size'],
                "</td></tr>";
}
echo "</table></div>";
?>

The values for shelf,food, dateIn display fine but I cannot get container.size to show any value. Can anyone see where I'm screwing this up? Thanks in advance.

2
  • Just change $entry['container.size'] to $entry['container']['size'] Commented Sep 26, 2020 at 14:10
  • Geez! That did it. Thanks so much Slava. Commented Sep 26, 2020 at 19:17

1 Answer 1

1

Just change your code like:

<?php
require '../vendor/autoload.php';
$connection = new MongoDB\Client("mongodb://localhost:27017");
$collection = $connection->everything->foodstore;
echo "<div align='center'>";
$result = $collection->find([]);
echo "<table>";
foreach ($result as $entry){
        echo "<tr><td>",$entry['shelf'],
                "</td><td>",$entry['food'],
                "</td><td>",$entry['dateIn'],
                "</td><td>",$entry['container']['size'], //here changed
                "</td></tr>";
}
echo "</table></div>";
?>
Sign up to request clarification or add additional context in comments.

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.