[MongoDB learning notes] - use MongoDB for CRUD operation

Author: Huan Hao

Source: Hang Seng LIGHT cloud community

summary

MongoDB is a persistent document oriented database for storing and processing data in the form of documents.

Like other database management systems, MongoDB can manage and interact with data through four basic types of data operations:

  • C: Create an operation that involves writing data to the database
  • R: A read operation that queries the database to retrieve data from it
  • U: Update operation to change the existing data in the database
  • D: Delete operation to permanently delete data from the database

The above four operations are collectively referred to as CRUD operations. This paper mainly explains the principles and commands of these four operations.

Specific operation

Connect to MongoDB Server

First, connect to the local or remote MongoDB Server before operation, as shown in the following figure:

After you successfully connect to the MongoDB database, you can start creating new documents.

create documents

First, focus on how to create data documents in MongoDB

For example, create an Oriental Pearl spot object, and the relevant information may include the country, city, coordinates, etc.

{
    "name": "The Oriental Pearl",
    "country": "China",
    "city": "Shanghai",
    "location": {
        "lat": 121.537,
        "lng": 31.258
    }
}

MongoDB documents are written in BSON, which is a binary form of JSON and a convenient and readable data format. All data in a BSON or JSON document is represented as fields and value pairs in the form of field: value.

The document consists of four fields, first the name of the scenic spot, followed by the city and country. All three fields contain strings. The last field coordinate: location, is a nested document that specifies the location coordinates of scenic spots.

insertOne

Use the insertOne method to insert this document into a new collection called spots. As the name suggests, insertOne is used to create a single document rather than multiple documents at once.

On the command line, run the following command:

db.spots.insertOne(
    {
        "name": "The Oriental Pearl",
        "country": "China",
        "city": "Shanghai",
        "location": {
            "lat": 121.537,
            "lng": 31.258
        }
    }
)

# output
{
    "acknowledged" : true,
    "insertedId" : ObjectId("61b5d4963d2fc20a8483df1a")
}

Before executing this insertOne method, you need to ensure that the spots collection is not created.

By executing the sample insertOne() method, it not only inserts the document into the collection, but also automatically creates the collection. The output of this operation informs you that it has been successfully executed and provides the ObjectId it automatically generates for the new document: 61b5d4963d2fc20a8483df1a

In MongoDB, each document in the collection must have a unique_ The id field is used as the primary key, so_ The id field is unique. If it is set when a new document is inserted_ id field, MongoDB will automatically generate an object identifier (in the form of ObjectId object) as the value of the _idfield.

After the document is created, you can verify whether the document has been inserted by checking the object count in the spots collection with the following command:

> db.spots.count()

# Output:
1

insertMany

If you need to create multiple documents, it will become very troublesome if you insert documents one by one through the insertOne method. Therefore, 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 new attraction information into the spots collection:

db.spots.insertMany([
  {"name": "the Imperial Palace", "city": "Beijing", "country": "China", "gps": { "lat": 116.403, "lng": 39.924 }},
  {"name": "the Great Wall", "city": "Beijing", "country": "China", "gps": { "lat": 106.384, "lng": 39.031 }},
  {"name": "White House", "city": "Washington", "country": "U.S.A", "gps": { "lat": 116.652, "lng": 40.121 }},
  {"name": "London Eye", "city": "London", "country": "britain", "gps": { "lat": 116.348, "lng": 34.430 }}
])

Notice the square brackets ([]) surrounding the six documents, which represent an array of documents. Within square brackets, multiple objects can appear one after another, separated by commas. When the MongoDB method requires multiple objects, the object list can be provided in the form of an array like this.

MongoDB will respond to multiple object identifiers, one for each newly inserted object:

# output
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("61b5d7ba3d2fc20a8483df1b"),
                ObjectId("61b5d7ba3d2fc20a8483df1c"),
                ObjectId("61b5d7ba3d2fc20a8483df1d"),
                ObjectId("61b5d7ba3d2fc20a8483df1e")
        ]
}

You can verify that the document has been inserted by checking the number of objects in the spots collection:

> db.spots.count()
# Output:
5

consult your documentation

Through the creation operation, some documents are stored in the spots collection, and the database can be queried to retrieve these documents and read their data. This step first outlines how to query all documents in a given collection, and then describes how to use filters to narrow the list of retrieved documents.

find

After completing the previous step, you can use the find() method to retrieve all documents in a single operation:

> db.spots.find()

# Output:
{ "_id" : ObjectId("61b5d4963d2fc20a8483df1a"), "name" : "The Oriental Pearl", "country" : "China", "city" : "Shanghai", "location" : { "lat" : 121.537, "lng" : 31.258 } }
{ "_id" : ObjectId("61b5d7ba3d2fc20a8483df1b"), "name" : "the Imperial Palace", "city" : "Beijing", "country" : "China", "gps" : { "lat" : 116.403, "lng" : 39.924 } }
{ "_id" : ObjectId("61b5d7ba3d2fc20a8483df1c"), "name" : "the Great Wall", "city" : "Beijing", "country" : "China", "gps" : { "lat" : 106.384, "lng" : 39.031 } }
{ "_id" : ObjectId("61b5d7ba3d2fc20a8483df1d"), "name" : "White House", "city" : "Washington", "country" : "U.S.A", "gps" : { "lat" : 116.652, "lng" : 40.121 } }
{ "_id" : ObjectId("61b5d7ba3d2fc20a8483df1e"), "name" : "London Eye", "city" : "London", "country" : "britain", "gps" : { "lat" : 116.348, "lng" : 34.43 } }

When this method is used without any parameters, it does not apply any filtering and requires MongoDB to return all objects available in the specified collection: spots.

Note that each of these objects has a name that you do not define_ id attribute. As mentioned earlier_ The id field is used as the primary key for their respective documents and is automatically created when the insertMany method was run in the previous step.

To make the output of the find() method more readable, you can use its pretty method printing function, as shown below:

db.spots.find().pretty()

# Output:
{
        "_id" : ObjectId("61b5d4963d2fc20a8483df1a"),
        "name" : "The Oriental Pearl",
        "country" : "China",
        "city" : "Shanghai",
        "location" : {
                "lat" : 121.537,
                "lng" : 31.258
        }
}
{
        "_id" : ObjectId("61b5d7ba3d2fc20a8483df1b"),
        "name" : "the Imperial Palace",
        "city" : "Beijing",
        "country" : "China",
        "gps" : {
                "lat" : 116.403,
                "lng" : 39.924
        }
}
following find() Method returns a single object by accepting a query filter document as a parameter. Query filter documents follow the same structure as documents inserted into a collection, consisting of fields and values, but they are used to filter query results.

The query filter documents used include _id Field to query the specified object with the object identifier as the value:

shell
db.spots.find({"_id": ObjectId("61b5d4963d2fc20a8483df1a")}).pretty()

# Output:
{
        "_id" : ObjectId("61b5d4963d2fc20a8483df1a"),
        "name" : "The Oriental Pearl",
        "country" : "China",
        "city" : "Shanghai",
        "location" : {
                "lat" : 121.537,
                "lng" : 31.258
        }
}

You can also effectively filter through other fields in the document:

db.spots.find({"country": "China"}).pretty()

# Output:
{
        "_id" : ObjectId("61b5d4963d2fc20a8483df1a"),
        "name" : "The Oriental Pearl",
        "country" : "China",
        "city" : "Shanghai",
        "location" : {
                "lat" : 121.537,
                "lng" : 31.258
        }
}
{
        "_id" : ObjectId("61b5d7ba3d2fc20a8483df1b"),
        "name" : "the Imperial Palace",
        "city" : "Beijing",
        "country" : "China",
        "gps" : {
                "lat" : 116.403,
                "lng" : 39.924
        }
}
{
        "_id" : ObjectId("61b5d7ba3d2fc20a8483df1c"),
        "name" : "the Great Wall",
        "city" : "Beijing",
        "country" : "China",
        "gps" : {
                "lat" : 106.384,
                "lng" : 39.031
        }
}

Query filter documents are very powerful and flexible, which can help us query data efficiently.

summary

MongoDB provides a powerful query system that allows you to accurately select documents of interest according to complex standards. In the future, we will continue to share in detail the usage skills of MongoDB.

By studying the notes in this article, we can quickly get started with the basic CRUD operation of mongo. Of course, we need to practice by ourselves after learning.

Want to learn more from technology bosses? Where to discuss the problems encountered in development? How to obtain massive financial technology resources?

Hang Seng LIGHT cloud community , the financial technology professional community platform built by Hang Seng electronics shares practical technology dry goods, resource data and financial technology industry trends, and embraces all financial developers.

Scan the QR code of the applet below and join us!

Keywords: Database MongoDB

Added by merylvingien on Wed, 22 Dec 2021 20:00:18 +0200