Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

print mongodb array field values of document using php

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

question from:https://stackoverflow.com/questions/65861529/print-mongodb-array-field-values-of-document-using-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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 ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...