Hey my friends, a new post about this war. I don't know which is better, but I'll try to figure it out. I hope y'all enjoy this series. Here we go!
It's regular in the job environment to have to connect to databases in this case, we're going to connect with Mongodb.
You only need to have to install Mongodb in your SO or you can use Mongo Atlas for creating a Mongo database.
If you use vscode for coding I recommend you my plugin Mongodb-dly GUI
Python
First, you need to install a driver called "pymongo" this driver is to connect to the database and can find, insert, update and delete in this database. With this driver you can do a develop to save your data in Mongodb
python -m pip install pymongo
Here is the code of python, I'm going to add comments into language for explaining all methods or functions
from pymongo import MongoClient
from bson.objectid import ObjectId
from pprint import pprint
class CRUD():
def __init__(self, uri, dbname, collection):
self.client = MongoClient(uri)
self.collection = self.client[dbname][collection]
def create(self, data):
return self.collection.insert_one(data).inserted_id
def find(self, query={}):
print('Find by query')
for result in self.collection.find(query):
pprint(result)
def findOne(self, query):
result = self.collection.find_one(query)
print('Find One')
return result
def update(self, id, data):
return self.collection.update_one({'_id': ObjectId(id)}, {'$set': data}).modified_count
def delete(self, id):
return self.collection.delete_one({'_id': ObjectId(id)}).deleted_count
onepiece = CRUD('mongodb://localhost:27017', "onepiece", "crews")
crew = onepiece.findOne({"captain": "Luffy"})
id = onepiece.create({
'name': 'Red-Haired Pirates',
'ship': 'Red Force',
'captain': 'Shanks',
'members': ['Beckman', 'Roux', 'Yasopp']
})
crew['members'].append("Chopper")
print(f"Documents updated: {onepiece.update(crew['_id'], crew)}")
onepiece.find()
print(f"Documents deleted: {onepiece.delete(id)}")
onepiece.find()
PHP
First, you need to install a driver called "mongodb" this driver is to connect to the database and can find, insert, update and delete in this database. With this driver you can do a develop to save your data in Mongodb.
apt install php-mongodb
Here is the code of PHP, I'm going to add comments into language for explaining all methods or functions. Here, it's not necessary to import the driver because when you install php-mongodb you can use the driver by default.
<?php
class CRUD
{
public function __construct($uri, $dbname, $collection)
{
$this->manager = new MongoDB\Driver\Manager($uri);
$this->collection = $dbname . '.' . $collection;
}
public function create($data)
{
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert($data);
$this->manager->executeBulkWrite($this->collection, $bulk);
return $data['_id'];
}
public function find($filter = [])
{
echo "Find \n";
$query = new MongoDB\Driver\Query($filter);
$cursor = $this->manager->executeQuery($this->collection, $query);
var_dump($cursor->toArray());
}
public function findOne($filter = [])
{
echo "Find One \n";
$options = [
'limit' => 1,
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $this->manager->executeQuery($this->collection, $query);
return $cursor->toArray()[0];
}
public function update($id, $data)
{
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
['_id' => new MongoDB\BSON\ObjectId($id)],
['$set' => $data],
);
return $this->manager->executeBulkWrite($this->collection, $bulk);
}
public function delete($id)
{
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['_id' => new MongoDB\BSON\ObjectId($id)]);
return $this->manager->executeBulkWrite($this->collection, $bulk);
}
}
$onepiece = new CRUD("mongodb://localhost:27017", "onepiece", "crews");
$crew = $onepiece->findOne(["captain" => "Luffy"]);
$id = $onepiece->create([
'_id' => new MongoDB\BSON\ObjectId,
'name' => 'Red-Haired Pirates',
'ship' => 'Red Force',
'captain' => 'Shanks',
'members' => ['Beckman', 'Roux', 'Yasopp'],
]);
array_push($crew->members, "Robin");
echo "Documentos actualizados: " . $onepiece->update($crew->_id, $crew)->getModifiedCount() . "\n";
$onepiece->find();
echo "Documentos eliminados: " . $onepiece->delete($id)->getDeletedCount() . "\n";
$onepiece->find();
?>
Javascript
First, you need install a module called "mongodb" this module is for connect to database and can find, insert, update and delete into this database. With this module you can do a develop to save your data in Mongodb.
For this example, I did all code with async/await method.
npm install mongodb
Here is code of Javascript, I'm going to add comments into language for explain all methods or functions.
const { MongoClient, ObjectID } = require('mongodb');
class CRUD {
constructor(url, dbname, collection) {
this.client = new MongoClient(url, { useUnifiedTopology: true });
this.client.connect();
this.dbname = dbname;
this.collection = collection;
}
async create(data) {
const result = await this.client
.db(this.dbname)
.collection(this.collection)
.insertOne(data);
return result.ops[0]._id;
}
async find(query = {}) {
const result = await this.client
.db(this.dbname)
.collection(this.collection)
.find(query)
.toArray();
console.log(result);
}
async findOne(query = {}) {
return this.client
.db(this.dbname)
.collection(this.collection)
.findOne(query);
}
async update(id, data) {
const result = await this.client
.db(this.dbname)
.collection(this.collection)
.updateOne(
{ _id: new ObjectID(id) },
{
$set: data
}
);
return result.modifiedCount;
}
async delete(id) {
const result = await this.client
.db(this.dbname)
.collection(this.collection)
.deleteOne({ _id: new ObjectID(id) });
return result.deletedCount;
}
}
main = async () => {
const onepiece = new CRUD('mongodb://localhost:27017', 'onepiece', 'crews');
const crew = await onepiece.findOne({ captain: 'Luffy' });
const id = await onepiece.create({
name: 'Red-Haired Pirates',
ship: 'Red Force',
captain: 'Shanks',
members: ['Beckman', 'Roux', 'Yasopp']
});
crew.members.push('Franky');
console.log(
'Documentos actualizados: ' + (await onepiece.update(crew._id, crew))
);
await onepiece.find();
console.log('Documentos eliminados: ' + (await onepiece.delete(id)));
await onepiece.find();
};
main();
Conclusion
Structure: Change a lot, because every modules/drivers are different.
Lines: Python: 49, PHP: 75, Javascript: 83
Easy to understand: For me It's more clear python, because you can use this method almost the same way than in mongodb cli.
Would you like that I write more info about mongodb?
I hope you enjoy my post and remember that I am just a Dev like you!