One place for hosting & domains

      CRUD

      How To Perform CRUD operations in MongoDB


      The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      MongoDB is a persistent document-oriented database used to store and process data in the form of documents. As with other database management systems, MongoDB allows you to manage and interact with data through four fundamental types of data operations:

      • Create operations, which involve writing data to the database
      • Read operations, which query a database to retrieve data from it
      • Update operations, which change data that already exists in a database
      • Delete operations, which permanently remove data from a database

      These four operations are jointly referred to as CRUD operations.

      This tutorial outlines how to create new MongoDB documents and later retrieve them to read their data. It also explains how to update the data within documents, as well as how to delete documents when they are no longer needed.

      Prerequisites

      To follow this tutorial, you will need:

      Note: The linked tutorials on how to configure your server, install, and then secure MongoDB installation refer to Ubuntu 20.04. This tutorial concentrates on MongoDB itself, not the underlying operating system. It will generally work with any MongoDB installation regardless of the operating system as long as authentication has been enabled.

      Step 1 — Connecting to the MongoDB Server

      This guide involves using the MongoDB shell to interact with MongoDB. In order to follow along and practice CRUD operations in MongoDB, you must first connect to a MongoDB database by opening up the MongoDB shell.

      If your MongoDB instance is running on a remote server, SSH into that server from your local machine:

      Then connect to your MongoDB installation by opening up the MongoDB shell. Be sure to connect as a MongoDB user with privileges to write and read data. If you followed the prerequisite MongoDB security tutorial, you can connect as the administrative user you created in Step 1 of that guide:

      • mongo -u AdminSammy -p --authenticationDatabase admin

      After providing the user’s password, your terminal prompt will change to a greater-than sign (>). This means the shell is now ready to accept commands for the MongoDB server it’s connected to.

      Note: On a fresh connection, the MongoDB shell will automatically connect to the test database by default. You can safely use this database to experiment with MongoDB and the MongoDB shell.

      Alternatively, you could also switch to another database to run all of the example commands given in this tutorial. To switch to another database, run the use command followed by the name of your database:

      Now that you have connected to the MongoDB server using a MongoDB shell, you can move on to creating new documents.

      Step 2 — Creating Documents

      In order to have data that you can practice reading, updating, and deleting in the later steps of this guide, this step focuses on how to create data documents in MongoDB.

      Imagine that you’re using MongoDB to build and manage a directory of famous historical monuments from around the world. This directory will store information like each monument’s name, country, city, and geographical location.

      The documents in this directory will follow a format similar to this example, which represents The Pyramids of Giza:

      The Pyramids of Giza

      {
          "name": "The Pyramids of Giza",
          "city": "Giza",
          "country": "Egypt",
          "gps": {
              "lat": 29.976480,
              "lng": 31.131302
          }
      }
      

      This document, like all MongoDB documents, is written in BSON. BSON is a binary form of JSON, a human-readable data format. All data in BSON or JSON documents are represented as field-and-value pairs that take the form of field: value.

      This document consists of four fields. First is the name of the monument, followed by the city and the country. All three of these fields contain strings. The last field, called gps, is a nested document which details the monument’s GPS location. This location is made up of a pair of latitude and longitude coordinates, represented by the lat and lng fields respectively, each of which hold floating point values.

      Note: You can learn more about how MongoDB documents are structured in our conceptual article An Introduction to Document-Oriented Databases.

      Insert this document into a new collection called monuments using the insertOne method. As its name implies, insertOne is used to create individual documents, as opposed to creating multiple documents at once.

      In the MongoDB shell, run the following operation:

      • db.monuments.insertOne(
      • {
      • "name": "The Pyramids of Giza",
      • "city": "Giza",
      • "country": "Egypt",
      • "gps": {
      • "lat": 29.976480,
      • "lng": 31.131302
      • }
      • }
      • )

      Notice that you haven’t explicitly created the monuments collection before executing this insertOne method. MongoDB allows you to run commands on non-existent collections freely, and the missing collections only get created when the first object is inserted. By executing this example insertOne() method, not only will it insert the document into the collection but it will also create the collection automatically.

      MongoDB will execute the insertOne method and insert the requested document representing the Pyramids of Giza. The operation’s output will inform you that it executed successfully, and also provides the ObjectId which it generated automatically for the new document:

      Output

      { "acknowledged" : true, "insertedId" : ObjectId("6105752352e6d1ebb7072647") }

      In MongoDB, each document within a collection must have a unique _id field which acts as a primary key. You can include the _id field and provide it with a value of your own choosing, as long as you ensure each document’s _id field will be unique. However, if a new document omits the _id field, MongoDB will automatically generate an object identifier (in the form of an ObjectId object) as the value for the _id field.

      You can verify that the document was inserted by checking the object count in the monuments collection:

      Since you’ve only inserted one document into this collection, the count method will return 1:

      Output

      1

      Inserting documents one by one like this would quickly become tedious if you wanted to create multiple documents. MongoDB provides the insertMany method which you can use to insert multiple documents in a single operation.

      Run the following example command, which uses the insertMany method to insert six additional famous monuments into the monuments collection:

      • db.monuments.insertMany([
      • {"name": "The Valley of the Kings", "city": "Luxor", "country": "Egypt", "gps": { "lat": 25.746424, "lng": 32.605309 }},
      • {"name": "Arc de Triomphe", "city": "Paris", "country": "France", "gps": { "lat": 48.873756, "lng": 2.294946 }},
      • {"name": "The Eiffel Tower", "city": "Paris", "country": "France", "gps": { "lat": 48.858093, "lng": 2.294694 }},
      • {"name": "Acropolis", "city": "Athens", "country": "Greece", "gps": { "lat": 37.970833, "lng": 23.726110 }},
      • {"name": "The Great Wall of China", "city": "Huairou", "country": "China", "gps": { "lat": 40.431908, "lng": 116.570374 }},
      • {"name": "The Statue of Liberty", "city": "New York", "country": "USA", "gps": { "lat": 40.689247, "lng": -74.044502 }}
      • ])

      Notice the square brackets ([ and ]) surrounding the six documents. These brackets signify an array of documents. Within square brackets, multiple objects can appear one after another, delimited by commas. In cases where the MongoDB method requires more than one object, you can provide a list of objects in the form of an array like this one.

      MongoDB will respond with several object identifiers, one for each of the newly inserted objects:

      Output

      { "acknowledged" : true, "insertedIds" : [ ObjectId("6105770952e6d1ebb7072648"), ObjectId("6105770952e6d1ebb7072649"), ObjectId("6105770952e6d1ebb707264a"), ObjectId("6105770952e6d1ebb707264b"), ObjectId("6105770952e6d1ebb707264c"), ObjectId("6105770952e6d1ebb707264d") ] }

      You can verify that the documents were inserted by checking the object count in the monuments collection:

      After adding these six new documents, the expected output of this command is 7:

      Output

      7

      With that, you have used two separate insertion methods to create a number of documents representing several famous monuments. Next, you will read the data you just inserted with MongoDB’s find() method.

      Step 3 — Reading Documents

      Now that your collection has some documents stored within it, you can query your database to retrieve these documents and read their data. This step first outlines how to query all of the documents in a given collection, and then describes how to use filters to narrow down the list of retrieved documents.

      After completing the previous step, you now have seven documents describing famous monuments inserted into the monuments collection. You can retrieve all seven documents with a single operation using the find() method:

      This method, when used without any arguments, doesn’t apply any filtering and asks MongoDB to return all objects available in the specified collection, monuments. MongoDB will return the following output:

      Output

      { "_id" : ObjectId("6105752352e6d1ebb7072647"), "name" : "The Pyramids of Giza", "city" : "Giza", "country" : "Egypt", "gps" : { "lat" : 29.97648, "lng" : 31.131302 } } { "_id" : ObjectId("6105770952e6d1ebb7072648"), "name" : "The Valley of the Kings", "city" : "Luxor", "country" : "Egypt", "gps" : { "lat" : 25.746424, "lng" : 32.605309 } } { "_id" : ObjectId("6105770952e6d1ebb7072649"), "name" : "Arc de Triomphe", "city" : "Paris", "country" : "France", "gps" : { "lat" : 48.873756, "lng" : 2.294946 } } { "_id" : ObjectId("6105770952e6d1ebb707264a"), "name" : "The Eiffel Tower", "city" : "Paris", "country" : "France", "gps" : { "lat" : 48.858093, "lng" : 2.294694 } } { "_id" : ObjectId("6105770952e6d1ebb707264b"), "name" : "Acropolis", "city" : "Athens", "country" : "Greece", "gps" : { "lat" : 37.970833, "lng" : 23.72611 } } { "_id" : ObjectId("6105770952e6d1ebb707264c"), "name" : "The Great Wall of China", "city" : "Huairou", "country" : "China", "gps" : { "lat" : 40.431908, "lng" : 116.570374 } } { "_id" : ObjectId("6105770952e6d1ebb707264d"), "name" : "The Statue of Liberty", "city" : "New York", "country" : "USA", "gps" : { "lat" : 40.689247, "lng" : -74.044502 } }

      The MongoDB shell prints out all seven documents one by one and in full. Notice that each of these objects have an _id property which you didn’t define. As mentioned previously, the _id fields serve as their respective documents’ primary key, and were created automatically when you ran the insertMany method in the previous step.

      The default output from the MongoDB shell is compact, with each document’s fields and values printed in a single line. This can become difficult to read with objects containing multiple fields or nested documents, in particular.

      To make the find() method’s output more readable, you can use its pretty printing feature, like this:

      • db.monuments.find().pretty()

      This time, the MongoDB shell will print the documents on multiple lines, each with indentation:

      Output

      { "_id" : ObjectId("6105752352e6d1ebb7072647"), "name" : "The Pyramids of Giza", "city" : "Giza", "country" : "Egypt", "gps" : { "lat" : 29.97648, "lng" : 31.131302 } } { "_id" : ObjectId("6105770952e6d1ebb7072648"), "name" : "The Valley of the Kings", "city" : "Luxor", "country" : "Egypt", "gps" : { "lat" : 25.746424, "lng" : 32.605309 } } . . .

      Notice that in the two previous examples, the find() method was executed without any arguments. In both cases, it returned every object from the collection. You can apply filters to a query to narrow down the results.

      Recall from the previous examples that MongoDB automatically assigned The Valley of the Kings an object identifier with the value of ObjectId("6105770952e6d1ebb7072648"). The object identifier is not just the hexadecimal string inside the ObjectId(""), but the whole ObjectId object — a special datatype used in MongoDB to store object identifiers.

      The following find() method returns a single object by accepting a query filter document as an argument. Query filter documents follow the same structure as the documents you insert into a collection, consisting of fields and values, but they’re instead used to filter query results.

      The query filter document used in this example includes the _id field, with The Valley of the Kings’ object identifier as the value. To run this query on your own database, be sure to replace the highlighted object identifier with that of one of the documents stored in your own monuments collection:

      • db.monuments.find({"_id": ObjectId("6105770952e6d1ebb7072648")}).pretty()

      The query filter document in this example uses the equality condition, meaning the query will return any documents that have a field and value pair matching the one specified in the document. Essentially, this example tells the find() method to only return the documents whose _id value is equal to ObjectId("6105770952e6d1ebb7072648").

      After executing this method, MongoDB will return a single object matching the requested object identifier:

      Output

      { "_id" : ObjectId("6105770952e6d1ebb7072648"), "name" : "The Valley of the Kings", "city" : "Luxor", "country" : "Egypt", "gps" : { "lat" : 25.746424, "lng" : 32.605309 } }

      You can use quality condition on any other field from the document as well. To illustrate, try searching for monuments in France:

      • db.monuments.find({"country": "France"}).pretty()

      This method will return two monuments:

      Output

      { "_id" : ObjectId("6105770952e6d1ebb7072649"), "name" : "Arc de Triomphe", "city" : "Paris", "country" : "France", "gps" : { "lat" : 48.873756, "lng" : 2.294946 } } { "_id" : ObjectId("6105770952e6d1ebb707264a"), "name" : "The Eiffel Tower", "city" : "Paris", "country" : "France", "gps" : { "lat" : 48.858093, "lng" : 2.294694 } }

      Query filter documents are quite powerful and flexible, and they allow you to apply complex filters to collection documents.

      Step 4 — Updating Documents

      It’s common for documents within a document-oriented database like MongoDB to change over time. Sometimes, their structures must evolve along with the changing requirements of an application, or the data itself might change. This step focuses on how to update existing documents by changing field values in individual documents as well as and adding a new field to every document in a collection.

      Similar to the insertOne() and insertMany() methods, MongoDB provides methods that allow you to update either a single document or multiple documents at once. An important difference with these update methods is that, when creating new documents, you only need to pass the document data as method arguments. To update an existing document in the collection, you must also pass an argument that specifies which document you want to update.

      To allow users to do this, MongoDB uses the same query filter document mechanism in update methods as the one you used in the previous step to find and retrieve documents. Any query filter document that can be used to retrieve documents can also be used to specify documents to update.

      Try changing the name of Arc de Triomphe to the full name of Arc de Triomphe de l'Étoile. To do so, use the updateOne() method which updates a single document:

      • db.monuments.updateOne(
      • { "name": "Arc de Triomphe" },
      • {
      • $set: { "name": "Arc de Triomphe de l'Étoile" }
      • }
      • )

      The first argument of the updateOne method is the query filter document with a single equality condition, as covered in the previous step. In this example, { "name": "Arc de Triomphe" } finds documents with name key holding the value of Arc de Triomphe. Any valid query filter document can be used here.

      The second argument is the update document, specifying what changes should be applied during the update. The update document consists of update operators as keys, and parameters for each of the operator as values. In this example, the update operator used is $set. It is responsible for setting document fields to new values and requires a JSON object with new field values. Here, set: { "name": "Arc de Triomphe de l'Étoile" } tells MongoDB to set the value of field name to Arc de Triomphe de l'Étoile.

      The method will return a result telling you that one object was found by the query filter document, and also one object was successfully updated.

      Output

      { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

      Note: If the document query filter is not precise enough to select a single document, updateOne() will update only the first document returned from multiple results.

      To check whether the update worked, try retrieving all the monuments related to France:

      • db.monuments.find({"country": "France"}).pretty()

      This time, the method returns Arc de Triomphe but with its full name, which was changed by the update operation:

      Output

      { "_id" : ObjectId("6105770952e6d1ebb7072649"), "name" : "Arc de Triomphe de l'Étoile", "city" : "Paris", "country" : "France", "gps" : { "lat" : 48.873756, "lng" : 2.294946 } } . . .

      To modify more than one document, you can instead use the updateMany() method.

      As an example, say you notice there is no information about who created the entry and you’d like to credit the author who added each monument to the database. To do this, you’ll add a new editor field to each document in the monuments collection.

      The following example includes an empty query filter document. By including an empty query document, this operation will match every document in the collection and the updateMany() method will affect each of them . The update document adds a new editor field to each document, and assigns it a value of Sammy:

      • db.monuments.updateMany(
      • { },
      • {
      • $set: { "editor": "Sammy" }
      • }
      • )

      This method will return the following output:

      Output

      { "acknowledged" : true, "matchedCount" : 7, "modifiedCount" : 7 }

      This output informs you that seven documents were matched and seven were also modified.

      Confirm that the changes were applied:

      • db.monuments.find().pretty()

      Output

      { "_id" : ObjectId("6105752352e6d1ebb7072647"), "name" : "The Pyramids of Giza", "city" : "Giza", "country" : "Egypt", "gps" : { "lat" : 29.97648, "lng" : 31.131302 }, "editor" : "Sammy" } { "_id" : ObjectId("6105770952e6d1ebb7072648"), "name" : "The Valley of the Kings", "city" : "Luxor", "country" : "Egypt", "gps" : { "lat" : 25.746424, "lng" : 32.605309 }, "editor" : "Sammy" } . . .

      All the returned documents now have a new field called editor set to Sammy. By providing a non-existing field name to the $set update operator, the update operation will create missing fields in all matched documents and properly set the new value.

      Although you’ll likely use $set most often, many other update operators are available in MongoDB, allowing you to make complex alterations to your documents’ data and structure. You can learn more about these update operators in MongoDB’s official documentation on the subject.

      Step 5 — Deleting Documents

      There are times when data in the database becomes obsolete and needs to be deleted. As with Mongo’s update and insertion operations, there is a deleteOne() method, which removes only the first document matched by the query filter document, and deleteMany(), which deletes multiple objects at once.

      To practice using these methods, begin by trying to remove the Arc de Triomphe de l'Étoile monument you modified previously:

      • db.monuments.deleteOne(
      • { "name": "Arc de Triomphe de l'Étoile" }
      • )

      Notice that this method includes a query filter document like the previous update and retrieval examples. As before, you can use any valid query to specify what documents will be deleted.

      MongoDB will return the following result:

      Output

      { "acknowledged" : true, "deletedCount" : 1 }

      Here, the result tells you how many documents were deleted in the process.

      Check whether the document has indeed been removed from the collection by querying for monuments in France:

      • db.monuments.find({"country": "France"}).pretty()

      This time the method returns only single monument, The Eiffel Tower, since you removed the Arc de Triomphe de l'Étoile:

      Output

      { "_id" : ObjectId("6105770952e6d1ebb707264a"), "name" : "The Eiffel Tower", "city" : "Paris", "country" : "France", "gps" : { "lat" : 48.858093, "lng" : 2.294694 }, "editor" : "Sammy" }

      To illustrate removing multiple documents at once, remove all the monument documents for which Sammy was the editor. This will empty the collection, as you’ve previously designated Sammy as the editor for every monument:

      • db.monuments.deleteMany(
      • { "editor": "Sammy" }
      • )

      This time, MongoDB lets you know that this method removed six documents:

      Output

      { "acknowledged" : true, "deletedCount" : 6 }

      You can verify that the monuments collection is now empty by counting the number of documents within it:

      Output

      0

      Since you’ve just removed all documents from the collection, this command returns the expected output of 0.

      Conclusion

      By reading this article, you became familiar with the concept of CRUD operations — Create, Read, Update and Delete — the four essential components of data management. You can now insert new documents into a MongoDB database, modify existing ones, retrieve documents already present in a collection, and also delete documents as needed.

      Be aware, though, that this tutorial covered only one fundamental way of query filtering. MongoDB offers a robust query system allowing to precisely select documents of interest against complex criteria. To learn more about creating more complex queries, we encourage you to check out the official MongoDB documentation on the subject.



      Source link

      How To Perform CRUD Operations in MongoDB Using PyMongo on Ubuntu 20.04


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      MongoDB is a general-purpose, document-oriented, NoSQL database program that uses JSON-like documents to store data. Unlike tabular relations used in relational databases, JSON-like documents allow for flexible and dynamic schemas while maintaining simplicity. In general, NoSQL databases have the ability to scale horizontally, making them suitable for big data and real-time applications.

      A database driver or connector is a program that connects an application to a database program. To perform CRUD operations in MongoDB using Python, a driver is required to establish the communication channel. PyMongo is the recommended driver for working with MongoDB from Python.

      In this guide, you will write a Python script that creates, retrieves, updates, and deletes data in a locally installed MongoDB server on Ubuntu 20.04. In the end, you will acquire relevant skills to understand the underlying concepts in how data moves across MongoDB and a Python application.

      Prerequisites

      Before you move forward with this guide, you will need the following:

      Step 1 — Setting Up PyMongo

      In this step, you will install PyMongo, the recommended driver for MongoDB from Python. As a collection of tools for working with MongoDB, PyMongo facilitates database requests using syntax and an interface native to Python.

      To enable PyMongo, open your Ubuntu terminal and install from the Python Package Index. It is recommended to install PyMongo within a virtual environment in order to isolate your Python project. Refer to this guide if you missed how to set up a virtual environment in the prerequisites.

      pip3 refers to the Python3 version of the popular pip package installer for Python. Note that within the Python 3 virtual environment you can use the command pip instead of pip3.

      Now, open the Python interpreter with the command below. The interpreter is a virtual machine that operates like a Unix shell, where you can execute Python code interactively.

      You are in the interpreter when you get an output similar to what’s below:

      Output

      Python 3.8.5 (default, Jan 27 2021, 15:41:15) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.

      With a successful output, import pymongo in the Python interpreter:

      Using the import statement, you can access the pymongo module and its code in your terminal. The import statement will run without raising exceptions.

      On the next line, import getpass.

      • from getpass import getpass

      getpass is a module for managing password inputs. The module prompts you for a password without showing an input, and adds a security mechanism to prevent displaying passwords as plaintext.

      Here, make a connection with MongoClient to enable a MongoDB instance of your database. Declare a variable client to hold the MongoClient instance with host, username, password, and authMechanism as arguments:

      • client = pymongo.MongoClient('localhost', username="username", password=getpass('Password: '), authMechanism='SCRAM-SHA-256')

      To connect to MongoDB with authorization enabled, MongoClient requires four arguments:

      • host - the hostname of the server on which MongoDB is installed. Since Mongo is local in this context, use localhost.
      • username and password - authorization credentials created after enabling authentication in MongoDB.
      • authMechanism - SCRAM-SHA-256 is the default authentication mechanism supported by a cluster configured for authentication with MongoDB 4.0 or later.

      Once you’ve established the client connection, you can now interact with your MongoDB instance.

      Step 2 — Testing Databases and Collections

      In this step, you will get familiar with NoSQL concepts such as collections and documents as applied to MongoDB.

      MongoDB supports managing multiple independent databases within a MongoClient instance. You can access or create a database using attribute style on a MongoClient instance. Declare a variable db and assign the new database as an attribute of client:

      In this context, the workplace database keeps track of employee records you will add such as the employee’s name and role.

      Next, create a collection. Like tables in relational databases, collections store a group of documents in MongoDB. In your Python interpreter, create an employees collection as an attribute of db and assign it to a variable of the same name:

      Create the employees collection as an attribute of db and assign it to a variable of the same name.

      Note: In MongoDB, databases, and collections are created lazily. This means that none of the above codes are actually executed until the first document is created.

      Now that you’ve reviewed collections, let’s look at how MongoDB represents documents, the basic structure for representing data.

      Step 3 — Performing CRUD Operations

      In this step, you will perform CRUD operations to manipulate data in MongoDB. Create, retrieve, update, and delete (CRUD) are the four basic operations in computer programming that one can perform to create persistent storage.

      To represent data in Python as JSON-like documents, dictionaries are used. Create a sample employee record with name and role attributes:

      • employee = {
      • "name": "Sammy",
      • "role": "Developer"
      • }

      As you can see, Python dictionaries are very similar in syntax to JSON documents. PyMongo converts Python dictionaries to JSON documents for scalable data storage.

      At this point, insert the employee record into the employees collection:

      • employees.insert_one(employee)

      Calling the insert_one() method on the employees collection, provide the employee record created earlier to be inserted. A successful insertion should return a successful output like below:

      Output

      <pymongo.results.InsertOneResult object at 0x7f8c5e3ed1c0>

      Now, verify you’ve successfully inserted the employee record and the collection. Make a query to find the employee you just created:

      • employees.find_one({"name": "Sammy"})

      Calling thefind_one() method on the employees collection with a name query returns a single matching document. This method is useful when you have only one document, or when you are interested in the first match.

      The output should look similar to this:

      Output

      {'_id': ObjectId('606ae5b2358ddf640da46894'), 'name': 'Sammy', 'role': 'Developer'}

      Note: When a document is inserted, a unique key _id is automatically added to the document if it does not already contain an _id key.

      If the need arises to modify existing documents, use the update_one() method. The update_one() method requires two arguments, query and update:

      • query - {"name": "Sammy"} - PyMongo will use this query parameter to find documents with elements that match.
      • update - { "$set": {"role": "Technical Writer"} } - The update parameter implements the $set operator, which replaces the value of a field with the specified value.

      Call the update_one() method on the employees collection:

      • employees.update_one({"name": "Sammy"}, { "$set": {"role": "Technical Writer"} })

      A successful update will return an output similar to this:

      Output

      <pymongo.results.UpdateResult object at 0x7f8c5e3eb940>

      To delete a single document, employ the delete_one() method. delete_one() requires a query parameter which specifies the document to delete. Execute the delete_one() method as an attribute of the employees collection with the name Sammy as a query parameter.

      • employees.delete_one({"name": "Sammy"})

      This will delete the only entry you have in your employees collection.

      Output

      <pymongo.results.DeleteResult object at 0x7f8c5e3c8280>

      Using the find_one() method again, it is apparent that you’ve successfully deleted Sammy’s employee record as nothing prints to the console.

      • employees.find_one({"name": "Sammy"})

      insert_one(), find_one(), update_one(), and delete_one() are great ways of getting started with performing CRUD operations in MongoDB with PyMongo.

      Conclusion

      In this guide, you have explored how to set up and configure PyMongo, the database driver, to connect Python code to MongoDB, as well as creating, retrieving, updating, and deleting documents. Although this guide focuses on introductory concepts, PyMongo offers more powerful and flexible ways of working with MongoDB. For instance, you can make bulk inserts, query for more than one document, add indexes to queries, and many more.

      To learn more about MongoDB management, see How To Back Up, Restore, and Migrate a MongoDB Database on Ubuntu 20.04 and How To Import and Export a MongoDB Database on Ubuntu 20.04.



      Source link

      Simple Laravel CRUD with Resource Controllers


      Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using resource controllers. Resource Controllers can make life much easier and takes advantage of some cool Laravel routing techniques. Today, we’ll go through the steps necessary to get a fully functioning CRUD application using resource controllers.

      For this tutorial, we will go through the process of having an admin panel to create, read, update, and delete (CRUD) a resource. Let’s use sharks as our example. We will also make use of Eloquent ORM.

      This tutorial will walk us through:

      • Setting up the database and models
      • Creating the resource controller and its routes
      • Creating the necessary views
      • Explaining each method in a resource controller

      To get started, we will need the controller, the routes, and the view files.

      You can view and clone a repo of all the code covered in this tutorial on GitHub

      Getting our Database Ready

      Shark Migration

      We need to set up a quick database so we can do all of our CRUD functionality. In the command line in the root directory of our Laravel application, let’s create a migration.

      • php artisan migrate:make create_sharks_table --table=sharks --create

      This will create our shark migration in app/database/migrations. Open up that file and let’s add name, email, and shark_level fields.

      app/database/migrations/####_##_##_######_create_sharks_table.php

      <?php
      
      use IlluminateDatabaseSchemaBlueprint;
      use IlluminateDatabaseMigrationsMigration;
      
      class CreatesharksTable extends Migration {
      
          /**
              * Run the migrations.
              *
              * @return void
              */
          public function up()
          {
              Schema::create('sharks', function(Blueprint $table)
              {
                  $table->increments('id');
      
                  $table->string('name', 255);
                  $table->string('email', 255);
                  $table->integer('shark_level');
      
                  $table->timestamps();
              });
          }
      
          /**
              * Reverse the migrations.
              *
              * @return void
              */
          public function down()
          {
              Schema::drop('sharks');
          }
      
      }
      

      Now from the command line again, let’s run this migration. Make sure your database settings are good in app/config/database.php and then run:

      php artisan migrate Our database now has a sharks table to house all of the sharks we CRUD (create, read, update, and delete). Read more about migrations at the Laravel docs.

      Eloquent Model for the sharks

      Now that we have our database, let’s create a simple Eloquent model so that we can access the sharks in our database easily. You can read about Eloquent ORM and see how you can use it in your own applications.

      In the app/models folder, let’s create a shark.php model.

      app/models/shark.php

      
      <?php
      
          class shark extends Eloquent
          {
      
          }
      

      That’s it! Eloquent can handle the rest. By default, this model will link to our sharks table and and we can access it later in our controllers.

      Creating the Controller

      From the official Laravel docs, on resource controllers, you can generate a resource controller using the artisan tool.

      Let’s go ahead and do that. This is the easy part. From the command line in the root directory of your Laravel project, type:

      php artisan controller:make sharkController This will create our resource controller with all the methods we need.

      app/controllers/sharkController.php

      <?php
      
      class sharkController extends BaseController {
      
          /**
              * Display a listing of the resource.
              *
              * @return Response
              */
          public function index()
          {
              //
          }
      
          /**
              * Show the form for creating a new resource.
              *
              * @return Response
              */
          public function create()
          {
              //
          }
      
          /**
              * Store a newly created resource in storage.
              *
              * @return Response
              */
          public function store()
          {
              //
          }
      
          /**
              * Display the specified resource.
              *
              * @param  int  $id
              * @return Response
              */
          public function show($id)
          {
              //
          }
      
          /**
              * Show the form for editing the specified resource.
              *
              * @param  int  $id
              * @return Response
              */
          public function edit($id)
          {
              //
          }
      
          /**
              * Update the specified resource in storage.
              *
              * @param  int  $id
              * @return Response
              */
          public function update($id)
          {
              //
          }
      
          /**
              * Remove the specified resource from storage.
              *
              * @param  int  $id
              * @return Response
              */
          public function destroy($id)
          {
              //
          }
      
      }
      

      Setting Up the Routes

      Now that we have generated our controller, let’s make sure our application has the routes necessary to use it. This is the other easy part (they actually might all be easy parts). In your routes.php file, add this line:

      app/routes.php

      <?php
      
          Route::resource('sharks', 'sharkController');
      

      This will automatically assign many actions to that resource controller. Now if you, go to your browser and view your application at example.com/sharks, it will correspond to the proper method in your sharkController.

      Actions Handled By the Controller

      HTTP Verb Path (URL) Action (Method) Route Name
      GET /sharks index sharks.index
      GET /sharks/create create sharks.create
      POST /sharks store sharks.store
      GET /sharks/{id} show sharks.show
      GET /sharks/{id}/edit edit sharks.edit
      PUT/PATCH /sharks/{id} update sharks.update
      DELETE /sharks/{id} destroy sharks.destroy

      Tip: From the command line, you can run php artisan routes to see all the routes associated with your application.

      The Views

      Since only four of our routes are GET routes, we only need four views. In our app/views folder, let’s make those views now.

      app
      └───views
          └───sharks
              │    index.blade.php
              │    create.blade.php
              │    show.blade.php
              │    edit.blade.php
      

      Making It All Work Together

      Now we have our migrations, database, and models, our controller and routes, and our views. Let’s make all these things work together to build our application. We are going to go through the methods created in the resource controller one by one and make it all work.

      Showing All Resources sharks.index

      Description URL Controller Function View File
      Default page for showing all the sharks. GET example.com/sharks index() app/views/sharks/index.blade.php

      Controller Function index()

      In this function, we will get all the sharks and pass them to the view.

      app/controllers/sharkController.php

      
      <?php
      
      ...
      
          /**
              * Display a listing of the resource.
              *
              * @return Response
              */
          public function index()
          {
              // get all the sharks
              $sharks = shark::all();
      
              // load the view and pass the sharks
              return View::make('sharks.index')
                  ->with('sharks', $sharks);
          }
      ...
      

      The View app/views/sharks/index.blade.php

      Now let’s create our view to loop over the sharks and display them in a table. We like using Twitter Bootstrap for our sites, so the table will use those classes.

      app/views/sharks/index.blade.php

      
      <!DOCTYPE html>
      <html>
      <head>
          <title>Shark App</title>
          <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
      </head>
      <body>
      <div class="container">
      
      <nav class="navbar navbar-inverse">
          <div class="navbar-header">
              <a class="navbar-brand" href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks') }}">shark Alert</a>
          </div>
          <ul class="nav navbar-nav">
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks') }}">View All sharks</a></li>
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks/create') }}">Create a shark</a>
          </ul>
      </nav>
      
      <h1>All the sharks</h1>
      
      <!-- will be used to show any messages -->
      @if (Session::has('message'))
          <div class="alert alert-info">{{ Session::get('message') }}</div>
      @endif
      
      <table class="table table-striped table-bordered">
          <thead>
              <tr>
                  <td>ID</td>
                  <td>Name</td>
                  <td>Email</td>
                  <td>shark Level</td>
                  <td>Actions</td>
              </tr>
          </thead>
          <tbody>
          @foreach($sharks as $key => $value)
              <tr>
                  <td>{{ $value->id }}</td>
                  <td>{{ $value->name }}</td>
                  <td>{{ $value->email }}</td>
                  <td>{{ $value->shark_level }}</td>
      
                  <!-- we will also add show, edit, and delete buttons -->
                  <td>
      
                      <!-- delete the shark (uses the destroy method DESTROY /sharks/{id} -->
                      <!-- we will add this later since its a little more complicated than the other two buttons -->
      
                      <!-- show the shark (uses the show method found at GET /sharks/{id} -->
                      <a class="btn btn-small btn-success" href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks/' . $value->id) }}">Show this shark</a>
      
                      <!-- edit this shark (uses the edit method found at GET /sharks/{id}/edit -->
                      <a class="btn btn-small btn-info" href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks/' . $value->id . '/edit') }}">Edit this shark</a>
      
                  </td>
              </tr>
          @endforeach
          </tbody>
      </table>
      
      </div>
      </body>
      </html>
      

      We can now show all of our sharks on a page. There won’t be any that show up currently since we haven’t created any or seeded our database with sharks. Let’s move on to the form to create a shark.

      index-blade

      Creating a New Resource sharks.create

      Description URL Controller Function View File
      Show the form to create a new shark. GET example.com/sharks/create create() app/views/sharks/create.blade.php

      Controller Function create()

      In this function, we will show the form for creating a new shark. This form will be processed by the store() method.

      app/controllers/sharkController.php

      <?php
      ...
          /**
              * Show the form for creating a new resource.
              *
              * @return Response
              */
          public function create()
          {
              // load the create form (app/views/sharks/create.blade.php)
              return View::make('sharks.create');
          }
      ...
      

      The View app/views/sharks/create.blade.php

      app/views/sharks/create.blade.php

      
      <!DOCTYPE html>
      <html>
      <head>
          <title>Shark App</title>
          <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
      </head>
      <body>
      <div class="container">
      
      <nav class="navbar navbar-inverse">
          <div class="navbar-header">
              <a class="navbar-brand" href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks') }}">shark Alert</a>
          </div>
          <ul class="nav navbar-nav">
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks') }}">View All sharks</a></li>
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks/create') }}">Create a shark</a>
          </ul>
      </nav>
      
      <h1>Create a shark</h1>
      
      <!-- if there are creation errors, they will show here -->
      {{ HTML::ul($errors->all()) }}
      
      {{ Form::open(array('url' => 'sharks')) }}
      
          <div class="form-group">
              {{ Form::label('name', 'Name') }}
              {{ Form::text('name', Input::old('name'), array('class' => 'form-control')) }}
          </div>
      
          <div class="form-group">
              {{ Form::label('email', 'Email') }}
              {{ Form::email('email', Input::old('email'), array('class' => 'form-control')) }}
          </div>
      
          <div class="form-group">
              {{ Form::label('shark_level', 'shark Level') }}
              {{ Form::select('shark_level', array('0' => 'Select a Level', '1' => 'Sees Sunlight', '2' => 'Foosball Fanatic', '3' => 'Basement Dweller'), Input::old('shark_level'), array('class' => 'form-control')) }}
          </div>
      
          {{ Form::submit('Create the shark!', array('class' => 'btn btn-primary')) }}
      
      {{ Form::close() }}
      
      </div>
      </body>
      </html>
      

      We will add the errors section above to show validation errors when we try to store() the resource.
      Tip: When using {{ Form::open() }}, Laravel will automatically create a hidden input field with a token to protect from cross-site request forgeries. Read more at the Laravel docs.

      We now have the form, but we need to have it do something when it the submit button gets pressed. We set this form’s action to be a POST to example.com/sharks. The resource controller will handle this and automatically route the request to the store() method. Let’s handle that now.

      Storing a Resource store()

      Description URL Controller Function View File
      Process the create form submit and save the shark to the database. POST example.com/sharks store() NONE

      As you can see from the form action and the URL, you don’t have to pass anything extra into the URL to store a shark. Since this form is sent using the POST method, the form inputs will be the data used to store the resource.

      To process the form, we’ll want to validate the inputs, send back error messages if they exist, authenticate against the database, and store the resource if all is good. Let’s dive in.

      Controller Function store()

      app/controllers/sharkController.php

      <?php
      ...
          /**
              * Store a newly created resource in storage.
              *
              * @return Response
              */
          public function store()
          {
              // validate
              // read more on validation at http://laravel.com/docs/validation
              $rules = array(
                  'name'       => 'required',
                  'email'      => 'required|email',
                  'shark_level' => 'required|numeric'
              );
              $validator = Validator::make(Input::all(), $rules);
      
              // process the login
              if ($validator->fails()) {
                  return Redirect::to('sharks/create')
                      ->withErrors($validator)
                      ->withInput(Input::except('password'));
              } else {
                  // store
                  $shark = new shark;
                  $shark->name       = Input::get('name');
                  $shark->email      = Input::get('email');
                  $shark->shark_level = Input::get('shark_level');
                  $shark->save();
      
                  // redirect
                  Session::flash('message', 'Successfully created shark!');
                  return Redirect::to('sharks');
              }
          }
      ...
      

      If there are errors processing the form, we will redirect them back to the create form with those errors. We will add them in so the user can understand what went wrong. They will show up in the errors section we setup earlier.

      Now you should be able to create a shark and have them show up on the main page! Navigate to example.com/sharks and there they are. All that’s left is showing a single shark, updating, and deleting.

      created

      Showing a Resource show()

      Description URL Controller Function View File
      Show one of the sharks. GET example.com/sharks/{id} show() app/views/sharks/show.blade.php

      Controller Function show()

      app/controllers/sharkController.php

      <?php
      
      ...
      
          /**
              * Display the specified resource.
              *
              * @param  int  $id
              * @return Response
              */
          public function show($id)
          {
              // get the shark
              $shark = shark::find($id);
      
              // show the view and pass the shark to it
              return View::make('sharks.show')
                  ->with('shark', $shark);
          }
      
      ...
      

      The View app/views/sharks/show.blade.php

      app/views/sharks/show.blade.php

      
      <!DOCTYPE html>
      <html>
      <head>
          <title>Shark App</title>
          <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
      </head>
      <body>
      <div class="container">
      
      <nav class="navbar navbar-inverse">
          <div class="navbar-header">
              <a class="navbar-brand" href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks') }}">shark Alert</a>
          </div>
          <ul class="nav navbar-nav">
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks') }}">View All sharks</a></li>
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks/create') }}">Create a shark</a>
          </ul>
      </nav>
      
      <h1>Showing {{ $shark->name }}</h1>
      
          <div class="jumbotron text-center">
              <h2>{{ $shark->name }}</h2>
              <p>
                  <strong>Email:</strong> {{ $shark->email }}<br>
                  <strong>Level:</strong> {{ $shark->shark_level }}
              </p>
          </div>
      
      </div>
      </body>
      </html>
      

      show

      Editing a Resource edit()

      Description URL Controller Function View File
      Pull a shark from the database and allow editing. GET example.com/sharks/{id}/edit edit() app/views/sharks/edit.blade.php

      To edit a shark, we need to pull them from the database, show the creation form, but populate it with the selected shark’s info. To make life easier, we will use form model binding. This allows us to pull info from a model and bind it to the input fields in a form. Just makes it easier to populate our edit form and you can imagine that when these forms start getting rather large this will make life much easier.

      Controller Function edit()

      app/controllers/sharkController.php

      
      <?php
      
      ...
      
          /**
              * Show the form for editing the specified resource.
              *
              * @param  int  $id
              * @return Response
              */
          public function edit($id)
          {
              // get the shark
              $shark = shark::find($id);
      
              // show the edit form and pass the shark
              return View::make('sharks.edit')
                  ->with('shark', $shark);
          }
      ...
      

      The View app/views/sharks/edit.blade.php

      app/views/sharks/edit.blade.php

      <!DOCTYPE html>
      <html>
      <head>
          <title>Shark App</title>
          <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
      </head>
      <body>
      <div class="container">
      
      <nav class="navbar navbar-inverse">
          <div class="navbar-header">
              <a class="navbar-brand" href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks') }}">shark Alert</a>
          </div>
          <ul class="nav navbar-nav">
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks') }}">View All sharks</a></li>
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks/create') }}">Create a shark</a>
          </ul>
      </nav>
      
      <h1>Edit {{ $shark->name }}</h1>
      
      <!-- if there are creation errors, they will show here -->
      {{ HTML::ul($errors->all()) }}
      
      {{ Form::model($shark, array('route' => array('sharks.update', $shark->id), 'method' => 'PUT')) }}
      
          <div class="form-group">
              {{ Form::label('name', 'Name') }}
              {{ Form::text('name', null, array('class' => 'form-control')) }}
          </div>
      
          <div class="form-group">
              {{ Form::label('email', 'Email') }}
              {{ Form::email('email', null, array('class' => 'form-control')) }}
          </div>
      
          <div class="form-group">
              {{ Form::label('shark_level', 'shark Level') }}
              {{ Form::select('shark_level', array('0' => 'Select a Level', '1' => 'Sees Sunlight', '2' => 'Foosball Fanatic', '3' => 'Basement Dweller'), null, array('class' => 'form-control')) }}
          </div>
      
          {{ Form::submit('Edit the shark!', array('class' => 'btn btn-primary')) }}
      
      {{ Form::close() }}
      
      </div>
      </body>
      </html>
      

      Note that we have to pass a method of PUT so that Laravel knows how to route to the controller correctly.

      Updating a Resource update()

      Description URL Controller Function View File
      Process the create form submit and save the shark to the database. PUT example.com/sharks update() NONE

      This controller method will process the edit form. It is very similar to store(). We will validate, update, and redirect.

      Controller Function update()

      app/controllers/sharkController.php

      
      <?php
      
      ...
      
          /**
              * Update the specified resource in storage.
              *
              * @param  int  $id
              * @return Response
              */
          public function update($id)
          {
              // validate
              // read more on validation at http://laravel.com/docs/validation
              $rules = array(
                  'name'       => 'required',
                  'email'      => 'required|email',
                  'shark_level' => 'required|numeric'
              );
              $validator = Validator::make(Input::all(), $rules);
      
              // process the login
              if ($validator->fails()) {
                  return Redirect::to('sharks/' . $id . '/edit')
                      ->withErrors($validator)
                      ->withInput(Input::except('password'));
              } else {
                  // store
                  $shark = shark::find($id);
                  $shark->name       = Input::get('name');
                  $shark->email      = Input::get('email');
                  $shark->shark_level = Input::get('shark_level');
                  $shark->save();
      
                  // redirect
                  Session::flash('message', 'Successfully updated shark!');
                  return Redirect::to('sharks');
              }
          }
      ...
      

      Deleting a Resource destroy()

      Description URL Controller Function View File
      Process the create form submit and save the shark to the database. DELETE example.com/sharks/{id} destroy() NONE

      The workflow for this is that a user would go to view all the sharks, see a delete button, click it to delete. Since we never created a delete button in our app/views/sharks/index.blade.php, we will create that now. We will also add a notification section to show a success message.

      We have to send the request to our application using the DELETE HTTP verb, so we will create a form to do that since a button won’t do.

      Alert: The DELETE HTTP verb is used when accessing the sharks.destroy route. Since you can’t just create a button or form with the method DELETE, we will have to spoof it by creating a hidden input field in our delete form.

      The View app/views/sharks/index.blade.php

      app/views/sharks/index.blade.php

      
      ...
      
          @foreach($sharks as $key => $value)
              <tr>
                  <td>{{ $value->id }}</td>
                  <td>{{ $value->name }}</td>
                  <td>{{ $value->email }}</td>
                  <td>{{ $value->shark_level }}</td>
      
                  <!-- we will also add show, edit, and delete buttons -->
                  <td>
      
                      <!-- delete the shark (uses the destroy method DESTROY /sharks/{id} -->
                      <!-- we will add this later since its a little more complicated than the other two buttons -->
                      {{ Form::open(array('url' => 'sharks/' . $value->id, 'class' => 'pull-right')) }}
                          {{ Form::hidden('_method', 'DELETE') }}
                          {{ Form::submit('Delete this shark', array('class' => 'btn btn-warning')) }}
                      {{ Form::close() }}
      
                      <!-- show the shark (uses the show method found at GET /sharks/{id} -->
                      <a class="btn btn-small btn-success" href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks/' . $value->id) }}">Show this shark</a>
      
                      <!-- edit this shark (uses the edit method found at GET /sharks/{id}/edit -->
                      <a class="btn btn-small btn-info" href="https://www.digitalocean.com/community/tutorials/{{ URL::to("sharks/' . $value->id . '/edit') }}">Edit this shark</a>
      
                  </td>
              </tr>
          @endforeach
          ...
      

      Now when we click that form submit button, Laravel will use the sharks.destroy route and we can process that in our controller.

      Controller Function destroy()

      app/controllers/sharkController.php

      <?php
      
      ...
      
          /**
              * Remove the specified resource from storage.
              *
              * @param  int  $id
              * @return Response
              */
          public function destroy($id)
          {
              // delete
              $shark = shark::find($id);
              $shark->delete();
      
              // redirect
              Session::flash('message', 'Successfully deleted the shark!');
              return Redirect::to('sharks');
          }
      ...
      

      Conclusion

      That’s everything! Hopefully we covered enough so that you can understand how resource controllers can be used in all sorts of scenarios. Just create the controller, create the single line in the routes file, and you have the foundation for doing CRUD.

      As always, let us know if you have any questions or comments. We’ll be expanding more on Laravel in the coming articles so if there’s anything specific, throw it in the comments or email us.

      Further Reading: For more Laravel, check out our Simple Laravel Series.



      Source link