Programming Languages war Python, PHP, Javascrip (Nodejs) Connect to Mongodb

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

# Import driver for connecting to Mongodb
from pymongo import MongoClient

# It's necessary to turn a string in an ObjectId
from bson.objectid import ObjectId

# It's not necessary, but It's a good way to show organized data.
from pprint import pprint

# Do you remember how to use the class? We have another example
class CRUD():

  # Method constructor, with 3 parameters, uri: "Connection to Mongodb", dbname: "Database's name", collection: "Collection's name"
  def __init__(self, uri, dbname, collection):
    # A method for connecting to database.
    self.client = MongoClient(uri)
    # Save into variable collection and dbname.
    self.collection = self.client[dbname][collection]

  # Method to create a new document.
  def create(self, data):
    return self.collection.insert_one(data).inserted_id

  # Method to find and print documents from the collection.
  def find(self, query={}):
    print('Find by query')
    for result in self.collection.find(query):
      pprint(result)

  # Method to find One Document from the collection.
  def findOne(self, query):
    result = self.collection.find_one(query)
    print('Find One')
    return result

  # Method to update One registry by Id.
  def update(self, id, data):
    # modified_count return count of registers updated.
    return self.collection.update_one({'_id': ObjectId(id)}, {'$set': data}).modified_count

  # Method to delete One registry by Id.
  def delete(self, id):
    # deleted_count return count of registers deleted.
    return self.collection.delete_one({'_id': ObjectId(id)}).deleted_count


# Initialize class.
onepiece = CRUD('mongodb://localhost:27017', "onepiece", "crews")

# Find one register.
crew = onepiece.findOne({"captain": "Luffy"})

# Create one register.
id = onepiece.create({
    'name': 'Red-Haired Pirates',
    'ship': 'Red Force',
    'captain': 'Shanks',
    'members': ['Beckman', 'Roux', 'Yasopp']
})

# Add a crew member with an append method for arrays.
crew['members'].append("Chopper")

# Update and print count of documents updated.
print(f"Documents updated: {onepiece.update(crew['_id'], crew)}")

# Print all registers from the collection after the update.
onepiece.find()

# Delete and print count of documents deleted.
print(f"Documents deleted: {onepiece.delete(id)}")

# Print all registers from the collection after deleting.
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
// Do you remember how to use the class? We have another example.
class CRUD
{

    // Method constructor, with 3 parameters, uri: "Connection to mongodb", dbname: "Database's name", collection: "Collection's name"
    public function __construct($uri, $dbname, $collection)
    {
        // Method for connecting to database.
        $this->manager    = new MongoDB\Driver\Manager($uri);
        // Way to call the database and collection.
        $this->collection = $dbname . '.' . $collection;
    }

    // Method to create a new document.
    public function create($data)
    {
        // Method for setting data into database.
        $bulk = new MongoDB\Driver\BulkWrite;
        // Method to insert.
        $bulk->insert($data);
        // Execute bulk.
        $this->manager->executeBulkWrite($this->collection, $bulk);
        // Return ObjectId, those methods don't permit to get ObjectId after insert.
        return $data['_id'];
    }

    // Method to find and print documents from the collection.
    public function find($filter = [])
    {
        echo "Find \n";
        // The filter should be an Array, so this method translates array in a query format.
        $query = new MongoDB\Driver\Query($filter);

        // Execute filter.
        $cursor = $this->manager->executeQuery($this->collection, $query);
        var_dump($cursor->toArray());
    }

    // Method to find One data from the collection.
    public function findOne($filter = [])
    {
        echo "Find One \n";
        // You should add options for getting only one registry.
        $options = [
            'limit' => 1,
        ];
        $query  = new MongoDB\Driver\Query($filter, $options);
        $cursor = $this->manager->executeQuery($this->collection, $query);
        return $cursor->toArray()[0];
    }

    // Method to update One registry by Id.
    public function update($id, $data)
    {
        $bulk = new MongoDB\Driver\BulkWrite;
        // Method to update.
        $bulk->update(
            ['_id' => new MongoDB\BSON\ObjectId($id)],
            ['$set' => $data],
        );
        return $this->manager->executeBulkWrite($this->collection, $bulk);
    }

    // Method to delete One registry by Id.
    public function delete($id)
    {
        $bulk = new MongoDB\Driver\BulkWrite;
        // Method to delete.
        $bulk->delete(['_id' => new MongoDB\BSON\ObjectId($id)]);

        return $this->manager->executeBulkWrite($this->collection, $bulk);
    }
}

// Initialize class.
$onepiece = new CRUD("mongodb://localhost:27017", "onepiece", "crews");

// Find one register.
$crew = $onepiece->findOne(["captain" => "Luffy"]);

// Create one register, here if you need to get id after create you should add id into array because this driver don't have any method for get this ObjectId after create.
$id = $onepiece->create([
    '_id'     => new MongoDB\BSON\ObjectId,
    'name'    => 'Red-Haired Pirates',
    'ship'    => 'Red Force',
    'captain' => 'Shanks',
    'members' => ['Beckman', 'Roux', 'Yasopp'],
]);

// Add a crew member with the array_push function for arrays.
array_push($crew->members, "Robin");

// Update and print count of documents updated.
echo "Documentos actualizados: " . $onepiece->update($crew->_id, $crew)->getModifiedCount() . "\n";

// Print all registers from the collection after the update.
$onepiece->find();

// Delete and print count of documents deleted.
echo "Documentos eliminados: " . $onepiece->delete($id)->getDeletedCount() . "\n";

// Print all registers from the collection after deleting.
$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.

// Import module for connect to Mongodb.
const { MongoClient, ObjectID } = require('mongodb');

// Do you remember how to use the class? We have another example.
class CRUD {
  // Method constructor, with 3 parameters, uri: "Connection to mongodb", dbname: "Database's name", collection: "Collection's name"
  constructor(url, dbname, collection) {
    // Method in initialize database.
    this.client = new MongoClient(url, { useUnifiedTopology: true });
    // Method for connecting to database.
    this.client.connect();
    this.dbname = dbname;
    this.collection = collection;
  }

  // Method to create a new document.
  async create(data) {
    const result = await this.client
      .db(this.dbname)
      .collection(this.collection)
      .insertOne(data);
    return result.ops[0]._id;
  }

  // Method to find and print documents from the collection.
  async find(query = {}) {
    const result = await this.client
      .db(this.dbname)
      .collection(this.collection)
      .find(query)
      .toArray();

    console.log(result);
  }

  // Method to find One data from the collection.
  async findOne(query = {}) {
    return this.client
      .db(this.dbname)
      .collection(this.collection)
      .findOne(query);
  }

  // Method to update One registry by Id.
  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;
  }

  // Method to delete One registry by Id.
  async delete(id) {
    const result = await this.client
      .db(this.dbname)
      .collection(this.collection)
      .deleteOne({ _id: new ObjectID(id) });
    return result.deletedCount;
  }
}


// I have to create a main function, because I developed with async/await.
main = async () => {

  // Initialize class.
  const onepiece = new CRUD('mongodb://localhost:27017', 'onepiece', 'crews');

  // Find one register.
  const crew = await onepiece.findOne({ captain: 'Luffy' });

  // Create one register.
  const id = await onepiece.create({
    name: 'Red-Haired Pirates',
    ship: 'Red Force',
    captain: 'Shanks',
    members: ['Beckman', 'Roux', 'Yasopp']
  });

  // Add a crew member to crew with the push method for arrays.
  crew.members.push('Franky');

  // Update and print count of documents updated .
  console.log(
    'Documentos actualizados: ' + (await onepiece.update(crew._id, crew))
  );

  // Print all registers from the collection after the update.
  await onepiece.find();

  // Delete and print count of documents deleted.
  console.log('Documentos eliminados: ' + (await onepiece.delete(id)));

  // Print all registers from the collection after deleting.
  await onepiece.find();
};

// Run main function.
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!

No Comments Yet