0

Hi I have a mongodb database where i store products and each product doc is like below :

enter image description here

Using php I want to print all instances of "user" from the "comments" array What I tried :

$collection=$db->products;

  $itemID = $_POST['itemID'];

  $cursor = $collection->findOne(["id"=>$itemID]); //find an item 
  //print all user names who commented on item 
  foreach($cursor['comments'] as $c){
          echo "<p> User : ".$c["user"]." </p>";
          }
  ";
  exit();

And I get :

Warning:  Invalid argument supplied for foreach()

This is the first time I do this so I would appreciate your help

1 Answer 1

1
  1. From the findOne() docs: As opposed to MongoCollection::find(), this method will return only the first result from the result set, and not a MongoCursor that can be iterated over.

( you need to use find().limit(1) to fetch single document if you want to iterate with forEach construction or you must remove the forEach method to be able to use the findOne() )

  1. If you need to iterate over the comments arrray elements and there is nothing found in the database it will be a problem , so you need to check first if the comments exist ...

  2. Before the end line there is ' "; ' that seems to need to be removed ...

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

2 Comments

I am returning a single document. I want to iterate over the comments array of just one document and print the results as html
Is the document found? , since it seems the foreach do not see the 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.