How to add a user to MongoDB using PHP?

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

How to add a user to MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , a year ago

@cali_green 

To add a user to MongoDB using PHP, you can use the MongoDBCollection class and its insertOne() method. Here's an example code snippet that demonstrates how to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
// Set up MongoDB connection
$mongo = new MongoDBClient("mongodb://localhost:27017");

// Select the database and collection
$collection = $mongo->mydatabase->users;

// Define the new user document
$user = [
    'username' => 'newuser',
    'password' => password_hash('mypassword', PASSWORD_DEFAULT),
    'email' => '[email protected]',
];

// Insert the new user document into the collection
$insertOneResult = $collection->insertOne($user);

// Check if the insertion was successful
if ($insertOneResult->getInsertedCount() == 1) {
    echo "User added successfully!";
} else {
    echo "Failed to add user!";
}
?>


In this example, we first establish a connection to MongoDB using the MongoDBClient class. Then, we select the database and collection where we want to add the new user. We define the new user as an associative array with three fields: username, password, and email. We use the password_hash() function to hash the user's password before storing it in the document.


Finally, we use the insertOne() method of the MongoDBCollection class to insert the new user document into the collection. The method returns a MongoDBInsertOneResult object, which we can use to check if the insertion was successful by calling the getInsertedCount() method.