MongoDB with PHP Cheatsheat

    科技2025-06-07  13

    Terminologies

    RDBMSMongoDBRDBMSMongoDBDatabaseDatabaseTableCollectionTuple/RowDocumentcolumnFieldPrimary KeyPrimary Key (Default key _id provided by mongodb itself)

    Install Composer

    composer require "mongodb/mongodb=^1.0.0"

    Insert in PHP file

    require 'vendor/autoload.php';

    Connect to MongoDB Client

    $client = new MongoDB\Client();

    Select Database

    $db = $client->dbname;

    Select Collection

    $collection = $db->collname;

    Shorthand Selection

    $collection = (new MongoDB\Client)->dbname->collectionName;

    Queries

    Get all documents $cursor = $collection->find();

    Iterate using for loop

    $collection->find().pretty() will display documents in pretty format.

    Get document(s) based on a single field

    Similar to Select * from table where attribute = value

    $cursor = $collection->findOne(array('email'=>$email)); $cursor = $collection->find({ status: "A" }, { item: 1, status: 1 }) //similar to Select item,status from table where status='A' //if any field:0, that field will not be shown

    $cursor["attributename"] will give value of that attribute

    limit(n) will return only n documents $cursor = $collection->find(array('email'=>'admin@example.com')); foreach ($cursor as $key){ echo $key['email']; } Get documnet(s) based on multiple fields $res = $coll->find(['email'=>'abc@xyz.com','password'=>'123']); //iterate using for loop Insert Document $result = $collection->insertOne([ 'username' => 'admin', 'email' => 'admin@example.com', 'name' => 'Admin User', ]);

    $result->getInsertedCount() will return the number of documents inserted.

    Insert Multiple Documents $res=$coll->insertMany([ ['email'=>'abc@xyz.com','password'=>'123'], ['email'=>'abc@xyz.com','password'=>'111'], ['email'=>'xyz@abc.com','password'=>'123'], ['email'=>'xyz@abc.com','password'=>'111']]); Delete Document $var= $collection->deleteOne( ["username"=>"admin"]); echo $var->getDeletedCount(); Delete Multiple Documents $var= $collection->deleteMany( ["username"=>"admin"]);

    $var->getDeletedCount() will return the number of documents deleted.

    Count $c = $coll->count();
    Processed: 0.009, SQL: 8