The CRUD operations of MongoDB

Source: Internet
Author: User
Tags findone mongodb query mongo shell

1. Preface

In the previous article, we introduced MongoDB. Now, let's look at how to do a regular crud operation in MongoDB. After all, as a storage system, it is the basic function of the data to be increased and censored operation.

The additions and deletions in MongoDB are different from the operations in our familiar relational database. In relational databases, such as MySQL, we typically use SQL statements to add (INSERT) Delete (delete) changes (SELECT) to a database. MongoDB uses the document for data manipulation during the operation of the data. When working with a database, document is used to represent the conditions that need to be queried and the data that needs to be updated, similar to the SQL statements in the relational database. Next, let's look at how to use document for CRUD operations in MongoDB.

Note: The CRUD operations described below are operational in MongoDB's MONGO shell. The MONGO Shell is a JavaScript interactive environment that is a client provided by MongoDB. Different languages have their own corresponding driver and corresponding operation API, but the principle is similar. I believe that through the introduction of CRUD operations in the MONGO shell, you can also extrapolate and manipulate MongoDB in different languages.

2. Insert operation

New in MongoDB to insert a new document into a collection.

If the collection does not exist, a new collection is added. This is very different from the relational database, where we need to define the schema and table structure of the database, which is a big difference between a NoSQL (MongoDB is a nosql) database and a relational database. In MongoDB, we can include several different structures in a collection document (not recommended, a collection preferably with the same format document, easy to maintain and use).

About the "_id" field, when we add a document to the collection, MongoDB needs a "_id" field in each new document, MongoDB takes this field as the primary key, Therefore, this field is required to be unique in collection. If the new document does not contain a "_id" field, the client of MongoDB adds a "_id" field with a value of Objectid type in the document If the MongoDB service finds that there is no "_id" field in the document when the document is added, Mongod adds a "_id" field with the Objectid type to the document.

MongoDB writes to a single document are atomic.

MongoDB provides the following ways to do new things:

    • Db.collection.insert ()
    • Db.collection.insertOne () 3.2 version added
    • Db.collection.insertMany () 3.2 version added
2.1 Db.collection.insert ()

The insert operation can either add a single document or add more than one document. If you add a single document, you pass the new document as a parameter to insert (), and if you add more than one document, an array of document is passed as an argument with an insert () function.

For example, we need to add a document to the "post" collection to indicate that a new article has been added to our blog, and we can do this:

Now, we have added a document to post this collection, which indicates that a new article has been added to the blog. We can see if there is a new document in the collection of the post now.

Here we use FindOne () to query, we can see that we have not included in the document "_id" field, so MongoDB automatically added a "_id" field for us.

The insert () function can add more than one document at a time, as long as an array of document is passed to the insert (), such as:

2.2 Db.collection.insertOne ()

The Insertone () function was added in version 3.2, which is used to add a single document. Examples are as follows:

2.3 Db.collection.insertMany ()

The Insertmany () function is a batch-incremented version of insert that supports adding more than one document at a time and is also a new function in version 3.2:

OK, let's briefly introduce the three functions of the next insert operation, below, we have added several document in the MongoDB database. Next, it's time to start learning the find operations to see the records that have been stored in MongoDB.

3. Query operation

MongoDB provides the Db.collection.find () function to perform a query operation, and the function returns a cursor that is used to traverse the query to the documents. The Find () function accepts two parameters, one is the filter condition, and the other is the projection.

Db.collection.find (<query filter>, <projection>)
    • <query filter> to find the document that meets the filter criteria
    • <projection> (projection) is used to specify which fields are returned in the document being found to limit the size of data transferred in the network. The concept of projection and the concept of projection in relational databases are basically consistent.

Now we can look at all the documents we have just added, through find (), let's see how to query:

If we do not pass any arguments, or pass a "{}" to the Find () function, then find () returns all the document in collection. Now, you can see all the documents we have just added.

Next, we'll look at the document titled "Third Post" by specifying the criteria, which we can do:

Find out, our query conditions are actually constructed in the form of document. In MongoDB, we can define different query conditions by constructing different document.

In addition to using specific fields to filter, we can also use query operators to do more flexible operations. We now need to find any one of the two post posts titled "Third Post" or "fifth post", which we can use $in operator to query:

In addition to using $in, MongoDB also provides a number of useful operators to help construct filtering conditions such as $lt, $gt, $and, $or , and so on.

3.1 Using the value in the child document as the filter condition

Now, let's assume that there is an article that is stored in document as follows:

Now we need to match the conditions in the internal document, for example, we need to find the record in author that name is Duke, and we can construct our filters like this:

Db.post.findOne ({"author": {"name": "Duke""Email": "[email protected]"}})

This is the result of the query.

We observe this filter condition and find the same structure as the filter above, which is the format of {"Field": "Value"}, except that this time "value" is no longer a normal value, but a document. In this way to filter, with some limitations, if we want to find author in name is Duke's record, we must fully specify the value of author, that is, the need for a full document. If you need to filter only the name and not the value of the email, we can construct the filter as follows:

Db.post.findOne ({"Author.name": "Duke"})

Query to the same result as above

However, this time we used the "Author.name" method to specify field. This query, similar to the point symbol structure of a member reference, can be used to filter the specified field in the embedded document. As you'll see later, for the value of the array type, you can also construct the filter in a similar way.

3.2 Using elements in an array as filter criteria

Next we'll look at how to use the values in the array to construct the filter condition. The simplest and easiest to think of is the whole array as a filter, similar to the above to the entire sub-document as a filter condition, we can construct this

Db.post.findOne ({"Comments": ["Comment One", "comment"]})

The results of the query are as follows:

However, there is no way to specify a value in the array as the filter condition. If you want to use one of the values in the array as a filter, we can construct the filter as a condition:

Db.post.find ({"Comments": "Comment"})

The results of the query are as follows:

In the end, the "pretty ()" method is used to format the output, outputting formatted data for easy observation, and no other use. We can see that the filter condition constructed in this way uses an element in the array to filter the records, as long as the array contains this element (regardless of the subscript of the element), then the record is filtered, somewhat like the in operation in the collection. This way you can match an element in an array.

Next, as we move closer, we need to match the elements of one of the subscript positions in the array, so we need to construct the filter using the same member reference (dot notation) that we mentioned above, using similar matching sub-document:

Db.post.find ({"comments.0": "Comment"})

The results of the query are as follows:

Here, we specify the matching condition using {"comments.0": "Comment"}: The value of the array "comments" Subscript 0 is "comment." In this way, it is possible to filter out the previous record where the subscript 1 is "comment." As you can see, when using array subscript to construct the filter condition, the subscript is starting from 0.

MongoDB provides a rich operator to support the construction of flexible filtering conditions, which is described here first. Because of the length of the relationship, here is no longer, the next time to write a separate article focused on the next MongoDB query operations. Next, let's look at how the update is done in MongoDB.

4. Update operation

MongoDB also supports the basic update operation, which provides 4 methods for updating:

    • Db.collection.updateOne () 3.2 version added
    • Db.collection.updateMany () 3.2 version added
    • Db.collection.update ()
    • Db.collection.replaceOne () 3.2 version added

These update methods support three parameters:

    • Filter criteria for filtering records, filtering out records that need to be updated, and filtering conditions similar to those used in query.
    • A new document that updates part of the value or replaces an entire document other than "_id".
    • A set of update options organized in the document format.

The update operation of MongoDB for a single document is atomic. MongoDB's handling of the "_id" primary key when it is updated is that the "_id" PRIMARY key of the updated document cannot be changed either by updating or replacing the document, and if a different "_id" is included in the substitution, the substitution fails, such as:

In the example above, we modified the original "_id" value to be 1, then replaced the update, and found that the update failed, suggesting that the "_id" value cannot be changed.

When we update, the new document size exceeds the size of the original document, the update operation will reapply for a larger space to hold the new document.

Next, let's look at the usage of these update APIs.

4.1 Db.collection.updateOne ()

The Updateone () function is a new API in version 3.2 that updates a matching document. Now that we need to update the document titled "First Post" in our Post collection, we want to add some comments, so we can construct our update expression:

Db.post.updateOne ({"title": "First post"}, {"$set": {"comments": ["Comment One"]}})

Now, we have a comment on our "first Post" article. Here we use the "$set" operator to set up a new field, and MongoDB's update operation provides some useful operators to help construct the UPDATE statement. The Updateone () function updates the first document that is matched to. If you want to update multiple document, we can use the Updatemany () function to support.

4.2 Db.collection.updateMany ()

The Updatemany () function can update all of the document to which it is matched. For example, we want to update all the articles, so that each article has a number of views of the field, indicating the number of times to browse. We can do this:

Db.post.updateMany ({}, {"$set": {"View": 0}})

As we can see, with the Updatemany () function, we have updated all the document so that each document contains a "View" field with an initial value of 0.

4.3 Replacing document

There are two APIs mentioned above, all of which update a field in document. In addition to updating individual fields in the document, they can be substituted for the entire document that matches (in addition to the "_id" property, any property can be replaced). As long as the update parameter is changed to an ordinary document (the structure of the document does not contain operators), the matching document can be replaced with the document in the parameter. When you replace the document with an update, it is important to note that the "_id" attribute in the original document cannot be changed, so the new document for substitution cannot contain the "_id" attribute, and if the "_id" attribute is included, the "_id" The property must be the same as the "_id" property of the document being updated.

In addition to the above two APIs can be used to replace Document,mongodb in the 3.2 version of the new Replaceone () function to replace the operation. Now we are replacing a document with Replaceone (), and we replace the document with "title" as "first Post" with the new document:

New Date ()})

Now, we have replaced the document "title" as "first post" for the new "title" as the document for "POST".

Finally, let's take a look at the top three API's synthesizer, which is the update () function, which basically contains all of the three APIs mentioned above, by default, the update () function updates the first document to match, if the "multi" option is set, Then you can update all of the document that matches to it.

Let's update the first document to match by using update ():

Db.post.update ({"title": "New Post"}, {"$set": {"View": 0}})

Okay, here's the update, and here's the last one to delete the action.

5. Delete operation

Here, I think we all already understand mongodb in the "Increase", "Change", "check" the function, next we look at the "delete" this function. MongoDB provides three APIs for delete operations, namely:

    • Db.collection.deleteOne ()
    • Db.collection.deleteMany () 3.2 version added
    • Db.collection.remove () 3.2 version added

Each of the three APIs supports a filter condition parameter that matches the document that satisfies the criteria and then deletes the operation.

From the literal meaning of the three APIs we can see that deleteone () deletes the first of all the document matches to, while Deletemany () and remove () Delete all the matching document.

Suppose we need to delete the document "title" as "New Post", we can use Deleteone () to manipulate

Db.post.deleteOne ({"title": "New Post"})

When we removed the document "title" as "New Post", we found that the document was actually deleted. Deleteone () is used to delete a single document, and if we need to delete all the document that satisfies the filter, we can use Deletemany () or remove ().

Now we want to delete all the articles with 0 views, then we can use Deletemany () or remove to achieve:

Db.post.remove ({"View": 0})

Because the view value of all the document that we store in the collection is 0, the above operation is equivalent to emptying our collection.

6. Summary

Well, here we have a brief description of the relevant CRUD operations in MongoDB. I believe we have some simple understanding of the basic operation of MongoDB.

Almost first wrote here, because the theme of the article is to introduce MongoDB crud operations, so many of the above details are not expanded, interested students can go through the MongoDB documents to understand, there is a chance, next time alone to carry out a good summary. After all, we learn something, we have to have a general understanding of the future, before we can have a deep, blindly pursuit of details, often lost direction.

The CRUD operations of MongoDB

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.