MongoDB CRUD Operations

Tram Ho

Introducing MongoDB

1. What is MongoDB?

  • MongoDB is a Document Database :
    • Each record in MongoDb is a document – a data structure consisting of field and value pairs.
    • MongoDB documents are similar to JSON objects.
    • Field values ​​can include other documents, an array, or arrays of documents.
  • The benefits of using documents are:
    • Documentation corresponds to natural data types in many programming languages.
    • Using embedded arrays and documents minimizes the effort involved in joining as a relational database.
    • The fields can change from document to document so the data structure can be easily changed.
  • Main features of MongoDB
    • High performance: MongoDB supports embedded data models that reduce I / O operations on the database system. At the same time, indexes support fast queries.
    • Powerful query language: MongoDB provides a rich query language for read and write operations (CRUD) as well as Data Aggregation, Text Search.
    • MongoDB is a distributed database, thus easily scalable horizontally, with high availability …
    • Support many storage tools.
    • Free MongoDB to use

2. The basics of MongoDB

2.1 Database

  • In MongoDB, the database contains collections of documents.
  • To select the database to use, in the mongo shell , use the command
  • If the DB does not yet exist, MongoDB will create a DB when you first store data for the database.

    insertOne () will create both myNewDB database and myNewCollection1 collection if they do not exist.

2.2 Collection

  • Collection is equivalent to a table in a relational database
  • Collection contains documents

2.3 Document

  • Document is equivalent to data record (data record) in relational database.
  • The document here is BSON document. BSON is a binary representation of a JSON document.
  • MongoDB documents consist of pairs (field: value) in the following structure:
  • The value here can be any BSON data type, be it another document, an array, or an array of documents, for example the following document contains values ​​of different types:

3. MongoDB CRUD Operations

3.1 Create Operations

  • Create or Insert add a new document to a collection. If the collection does not exist, insert creates the collection.
  • MongoDB provides two methods to insert a document into a collection
    • db.collection.insertOne () : insert a new document into a collection. If the document doesn’t have _id field, MongoDB will automatically add _id field with value of type ObjectId.

      insertOne () returns a document including the id of the newly inserted document and a Berkelleadge field (we will learn about this later):
    • db.collection.insertMany () : insert multiple documents into a collection, passing a method of documents array

      The example above inserts 3 new documents into the inventory collection. If the document does not specify a _id field, MongoDB adds the _id field with a value of type ObjectId to each document.

3.2 Read Operations

Read operation retrieves documents from a collection

  • To retrieve all documents in the collection, pass an empty document into the find method

    This action is equivalent to the following SQL:
  • Qualification Degree:

    To specify equal conditions, use the expression <field>:<value> :

    The following command retrieves documents with status equal to “D” from the inventory collection

    This action is equivalent to the following SQL:

  • Specify conditions using query operators:

    Syntax:

    For example, the following statement retrieves all documents from the inventory collection with status equal to “A” or “D”.

    The above statement corresponds to the following SQL statement:

    Refer to the Query and Projection Operators for more MongoDB query operators

  • AND query

    A combined query can specify conditions for multiple fields of the document. The following example retrieves all documents in the collection inventory with status field equal to “a” and qty field less than 30 ( $ lt )

    The above statement is equivalent to the following SQL statement:

    Refer to comparison operators for more comparison operators of MongoDB

  • OR query

    The following example retrieves documents in the collection whose status field is equal to “A” or qty is less than 30

    The above statement corresponds to the following SQL statement:

  • The query combines AND, OR

    The following example retrieves all documents in the collection whose status field is equal to “A” and the qty field is less than ( $ lt ) 30 or the item field begins with the letter p

    The above statement is equivalent to the following SQL statement:

3.3 Update Operations

  • Update operation edits documents that already exist in a collection. To update a document, MongoDB provides update operators including $ set .
  • To use the update operators, pass the update method to an update document

  • Some update operators, including $ set, will create fields if the field doesn’t exist
  • Update a document with db.collection.updateOne ()

    The following example will update the first document that has the item field equal to “paper”:

    • Use the $ set operator to update the size.uom field’s value to cm and the field’s value to “P”
    • Use the $ currentDate operator to update the value of the lastModified field to the current date. If lastModified does not exist, $ currentDate will create this field.
  • Update multiple Documents with db.collection.updateMany ()

    The following example updates all documents of the collection inventory whose qty field is less than 50

  • Repace a document

    To replace the entire contents of a document (with the exception of the _id field), passing the entire document as a second parameter of the db.collection.replaceOne () function .

    When replacing a document, the replacement document must include only field / value pairs, not include update operators

    The replacement document may have multiple fields from the original document. In the replacement document, you can omit the _id field because the _id field is immutable. However, if you include the _id field, it must have the same value as the current value.

    The following example replaces the first document from the collection inventory that has the item with “paper”

3.4 Delete Operation

The Delete operation removes the document from a collection.

  • To delete all documents from a collection, pass a document filter {} to the db.collection.deleteMany () method.
  • The following example deletes all documents from the collection inventory
  • Delete all documents that meet the conditions

    You can specify criteria or filters that identify documents to delete.

    To specify an equal condition, use the expression <field>: <value>

    Query operators can be used to specify conditions:

    The following example deletes all documents whose status field is equal to “A”.

  • Delete only one document that meets the conditions

    To delete only one document that matches the condition (if there are many documents that satisfy, then delete the first document), use db.collection.deleteOne ()

    The following example deletes the first document that has status equal to “D”

4. Summary

  • The above are the most commonly used CRUD methods in MongDB. In the following article, I will write more details about other query methods in MongoDB. Hope this article is helpful to you.
  • Reference source: https://docs.mongodb.com/manual/crud/
Share the news now

Source : Viblo