How to create a collection in MongoDB using PHP?

Member

by samara , in category: PHP Databases , a year ago

How to create a collection in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , a year ago

@samara 

To create a collection in MongoDB using PHP, you need to follow the below steps:

  1. First, connect to the MongoDB server using PHP MongoClient() class.
  2. Then, select a database using the selectDB() function.
  3. After selecting the database, use the createCollection() function to create the collection.


Below is an example code snippet to create a collection in MongoDB using PHP:

1
2
3
4
5
6
7
8
// Connect to MongoDB server
$mongoClient = new MongoClient();

// Select a database
$database = $mongoClient->selectDB('mydb');

// Create a collection
$collection = $database->createCollection('mycollection');


In the above example, we have created a collection named mycollection in the mydb database. You can replace these names with your own database and collection names.