RDBMS | MongoDB |
---|---|
RDBMS | MongoDB |
Database | Database |
Table | Collection |
Tuple/Row | Document |
column | Field |
Primary Key | Primary Key (Default key _id provided by mongodb itself) |
composer require "mongodb/mongodb=^1.0.0"
require 'vendor/autoload.php';
$client = new MongoDB\Client();
$db = $client->dbname;
$collection = $db->collname;
$collection = (new MongoDB\Client)->dbname->collectionName;
- 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();