PHP & MongoDB - Embedded Documents



Steps to Insert a Document with Embedded Document in a collection

First step to do any operation is to create a MongoDB Client instance.

$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);

Second step is to prepare and execute a command to select a collection and insert document with embedded document using insertOne() command.

// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');

// Define a Document
$document = [
   'title' => "MongoDB Overview", 
   'description' => 'MongoDB is no SQL database', 
   'by' => 'tutorials point',
   'url' => 'http://www.tutorialspoint.com',
   'comments' => [
      ['user' => "user1", 'message' => "My First Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
      ['user' => "user2", 'message' => "My Second Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
   ]];

// insert the document in the collection
$result = $collection->insertOne($document);

// Print result
printf("Inserted document ID: %s\n", $result->getInsertedId())

Example - Inserting a Document With Embedded Document in a MongoDB Collection

Try the following example to insert a document with embedded document in a MongoDB collection −

index.php

<?php
   require __DIR__ . '\vendor\autoload.php';
   $uri = "mongodb://localhost:27017";

   // connect to mongodb
   $client = new MongoDB\Client($uri);

   // select a collection of a database
   $collection = $client->selectCollection('myDb', 'sampleCollection');

   // Define a Document
   $document = [
      'title' => "MongoDB Overview", 
      'description' => 'MongoDB is no SQL database', 
      'by' => 'tutorials point',
      'url' => 'http://www.tutorialspoint.com',
      'comments' => [
         ['user' => "user1", 'message' => "My First Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
         ['user' => "user2", 'message' => "My Second Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
      ]];

   // insert the document in the collection
   $result = $collection->insertOne($document);

   // Print result
   printf("Inserted document ID: %s\n", $result->getInsertedId())
?>

Output

Access the index.php deployed on apache web server and verify the output.

Inserted document ID: 696ce141fed319cd950058cf
Advertisements