1024programmer Java Introduction to MongoDB Learning (3): MongoDB Add, Delete, Check and Modify

Introduction to MongoDB Learning (3): MongoDB Add, Delete, Check and Modify

For novices like us, the most important thing is not the management of the database, nor the performance of the database, nor the expansion of the database, but how to make good use of this database, that is, a database provides The most core function is addition, deletion, checking and modification. Because MongoDB stores data in document mode, when operating its data, it is also based on documents.

For novices like us, the most important thing is not the management of the database, nor the performance of the database, nor the expansion of the database, but how to make good use of this database, which is the core function provided by a database. , add, delete, check and modify.

Because MongoDB stores data in document mode, when operating its data, it is also based on documents. Then our implementation of adding, deleting, checking and modifying is also based on documents. Students who don’t know what documents are can take a look at the basic concepts introduced in the previous article.

1. Insert document

The basic method of inserting documents into a MongoDB collection is insert:

 single insert
 > document = {key : value}
 > db.collectionName.insert(document)
 Batch insert
 > documents = [{key : value}, {key : value}, {key : value}, ...]
 Pass in array
 > db.collectionName.insert(documents)
 for loop
 > for(var i = 0; i <documents.length; i++){
 ... db.people.insert(documents[i]);
 ... }

Because the collection is modeless, the documents in the collection can be of various types, so the insertion is very casual. If you want to insert a lot of data at once, you can use a for loop, or you can use batch insertion and pass in An array of documents. Because using a for loop to implement batch insertion will establish a TCP connection for each insertion, and passing in an array to implement batch insertion only has one TCP connection, so in terms of efficiency, the efficiency of for will be lower than passing in an array.

There is also a way to insert save. In the shell, you can use db.collectionName.function without brackets to see the implementation of the method. You can see the difference between insert and save. Let’s look at a small example:

 > db.people.find()
 { "_id" : 1, "name" : "mary", "age" : 20 }
 > db.people.insert({"_id" : 1, "name" : "amy", "age" : 22})
 E11000 duplicate key error index: test.people.$_id_ dup key: { : 1.0 }
 > db.people.save({"_id" : 1, "name" : "amy", "age" : 22})
 > db.people.find()
 { "_id" : 1, "name" : "amy", "age" : 22 }

Originally there is already a document in the people collection. If the primary key “_id” in the document we want to insert already has the same value in the collection, an error will be reported, but save will not. When there is no identical primary key, both insert and save will perform the insertion operation. When there is the same primary key, insert will report an error, and save will perform an update operation, replacing the original content with the content of the new document, which is the same as the update operation, so mary was replaced by amy.

When performing an insertion operation, the driver first converts the data into BSON form and then sends it to the database. It only checks whether the “_id” key is included and whether the document exceeds 4MB (the maximum document that can be inserted is 4MB, and if it exceeds It cannot be stored in the database) without performing other verifications and executing other codes, so it is far away from injection attacks and makes the database more secure.

2. Delete documents

The basic way to delete a document is remove:

 db.collectionName.remove()
 db.collectionName.remove({})
 db.collectionName.remove(condition)
 db.collectionName.drop()

The first three are to delete documents in the collection. The first and second are the same. They do not specify the conditions for deletion. This will delete all documents in the collection. The fourth is to delete the collection. Even the index has been deleted. If you want to clear the entire collection, it is faster to delete the collection directly than to delete all documents in the collection. The third one specifies a condition, such as deleting all documents named mary in the people collection:

 db.people.remove({"name" : "mary"})

3. Update documentation

The basic method of updating a document is update. Although it is mentioned above that save also has this effect when “_id” is the same, of course we generally do not use “_id” as the update condition:

 db.collectionName.uodate(condition, modifier, upsert, multi)

Update has four parameters. Condition is the query document, which is used to query the document to be modified. Modifier is the modifier document, which describes the modifications to the found document. Upsert means to insert the new document if there is no such document. , the default is false, multi indicates whether to update all queried documents, the default is false, so only the first queried document is updated. But we usually use the first two parameters, and if necessary, use the last two parameters. Because update operations are atomic, when many updates occur at the same time, the last update operation is the final result. Next we change the age of the document named mary to 20:

 > db.people.find()
 { "_id" : ObjectId("53a3a0b7abda49d7dfce102c"), "name" : "mary", "age" : 30, "country" : "US" }
 > db.people.update({"name" : "mary"}, {"age" : 20})
 > db.people.find()
 { "_id" : ObjectId("53a3a0b7abda49d7dfce102c"), "age"�.  

For the third method, specifying score.course and score.teacher, why are both queried? Obviously the second result is not what we want. When the course is computer, the teacher is not mary, but the course is chinese. When teacher is mary, so in the second result there is indeed score.course as computer, and score.teacher as mary exists at the same time, then this is combining the fields of the two documents to meet our requirements. Obviously this is not what we want, so we must use $elemMatc, which is method four, which ensures that our query is performed on the same document element in the array.

7).$where

$where can execute any Javascript as part of a query, so $where can do almost anything, but this approach must convert each document from BSON to a Javascript object, and then pass it through the $where expression To execute, and the index cannot be used. Therefore, using $where is a last resort, only use it when you are really desperate. The usage is also relatively simple, which is to operate this. If a document meets our customized conditions and returns true, then the document will be returned, such as:

 > db.fruit.find()
 { "_id" : ObjectId("53a412c7901e10bdd70adfa2"), "apple" : 2, "banana" : 6, "orange" : 3 }
 { "_id" : ObjectId("53a412d1901e10bdd70adfa3"), "apple" : 5, "banana" : 7, "orange" : 8 }
 db.fruit.find({"$where" : function(){
         for(var x in this){
                 for(var y in this){
                         if(this[x] / this[y] == 2){
                                 return true;
                         }
                 }
         }
 }})
 { "_id" : ObjectId("53a412c7901e10bdd70adfa2"), "apple" : 2, "banana" : 6, "orange" : 3 }

The database uses a cursor to return the execution results of find. The client's implementation of the cursor can usually effectively control the query results. It can limit the number of results, skip some results, and use any combination of keys in any direction. Sort the results, or perform some other powerful operation.

To use a cursor in the shell, you must first assign the query results to a variable, and then view the results one at a time through the cursor. If the query results are not assigned to variables, the shell will automatically iterate and print all the query results. The cursor provides two methods, hasNext returns whether there are any results, and next returns the next result to traverse the queried results. It also provides limit, skip, and sort methods to operate the results. Because the methods of the cursor object all return the cursor itself, these methods can be combined in any order. Such as:

 > db.people.find()
 { "_id" : ObjectId("53a3e01d33c516902a43a797"), "name" : "mary", "age" : 20 }
 { "_id" : ObjectId("53a3e02533c516902a43a798"), "name" : "amy", "age" : 23 }
 { "_id" : ObjectId("53a3e02d33c516902a43a799"), "name" : "join", "age" : 18 }
 { "_id" : ObjectId("53a3e03c33c516902a43a79a"), "name" : "jodan", "age" : 25 }
 { "_id" : ObjectId("53a3e04933c516902a43a79b"), "name" : "mical", "age" : 19 }
 > var cursor = db.people.find();
 > while(cursor.hasNext()){ obj = cursor.next(); print(obj.name); }
 mary
 amy
 join
 jodan
 mical
 > var cursor = db.people.find().limit(3);
 > while(cursor.hasNext()){ obj = cursor.next(); print(obj.name); }
 mary
 amy
 join
 > var cursor = db.people.find().skip(2);
 > while(cursor.hasNext()){ obj = cursor.next(); print(obj.name); }
 join
 jodan
 mical
 > var cursor = db.people.find().sort({"name" : 1});
 > while(cursor.hasNext()){ obj = cursor.next(); print(obj.name); }
 amy
 jodan
 join
 mary
 mical
 > var cursor = db.people.find().skip(2).limit(2).sort({"name" : 1});
 > while(cursor.hasNext()){ obj = cursor.next(); print(obj.name); }
 join
 mary

limit means adding an upper limit to the number of queried results. If the number of queried results is more than this upper limit, this number of results will be returned. If not, all results will be returned. Skip means to skip a certain number of results. If the number of queried results is less than this number, no documents will be returned. If it is more, this number of documents will be skipped and then returned. Sort means to sort the query results, specify the fields and specify the order, 1 is ascending order, -1 is descending order, and multiple fields can also be sorted at the same time.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/introduction-to-mongodb-learning-3-mongodb-add-delete-check-and-modify-3/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索