Monday, 19 August 2019

MongoDb PHP functions Questions and Answers

MongoDb PHP functions Questions and Answers

Question: How to connect to MongoDb with PHP?
$mongoObj = new MongoClient();



Question: How to select database?
$mongoDbObj = $mongoObj->mydb;



Question: How to create collection?
$collection = $mongoDbObj->createCollection("mycollectiontest");



Question: How to select collection?
$collection= $mongoDbObj->mycollectiontest;



Question: How to insert document in collection?
/* 1 document */
$document = array( 
      "title" => "MongoDB", 
      "description" => "MongoDB database", 
      "likes" => 100,
      "unlikes", 50
   );
   $collection->insert($document);
/* 2 document */
$document = array( 
      "title" => "MongoDB2", 
      "description" => "MongoDB database2", 
      "likes" => 1002,
      "unlikes", 502
   );
   $collection->insert($document); 



Question: How to list all documents?
   $cursor = $collection->find();
   foreach ($cursor as $document) {
      print_r($document);
   }

Output
Array
(
    [_id] => MongoId Object
        (
            [$id] => 57c3e73d9ba8827012000029
        )

    [title] => MongoDB
    [description] => MongoDB database
    [likes] => 100
    [0] => unlikes
    [1] => 50
)
Array
(
    [_id] => MongoId Object
        (
            [$id] => 57c3e7e79ba8821815000029
        )

    [title] => MongoDB2
    [description] => MongoDB database2
    [likes] => 1002
    [0] => unlikes
    [1] => 502
)
Array
(
    [_id] => MongoId Object
        (
            [$id] => 57c3e8fb9ba882181500002a
        )

    [title] => MongoDB2
    [description] => MongoDB database2
    [likes] => 1002
    [0] => unlikes
    [1] => 502
)



Question: How to list all documents (2nd way)?
 $cursor = $mongoObj->mydb->{'mycollectiontest'}->find();
/*$mongoObj is clinet, mydb is database, mydb is collections*/
   foreach ($cursor as $document) {
      print_r($document);
   }



Question: How to list all documents (3rd way)?
$query = array('title' => 'MongoDB');
$cursor = $collection->find($query);
   foreach ($cursor as $document) {
      print_r($document);
   }



Question: How to delete a document?
 $collection->remove(array("title"=>"MongoDB2"));



Question: How to update a document?
  $collection->update(array("title"=>"MongoDB"), 
 array('$set'=>array("description"=>"This is updated description")));