Play to MongoDB (iv): Elaborate insert, UPDATE, delete, and query

Source: Internet
Author: User
Tags bulk insert modifier sorted by name

Insert:

Use the Insert or Save method to insert a document into the target collection:

Db.person.insert ({"Name": "Ryan", "Age": 30});

Bulk INSERT is implemented using the Batchinsert method, which is very similar to the Insert method, except that it accepts an array of documents as a parameter. Sending dozens of, hundreds of, or even thousands of documents at a time can significantly increase the speed of insertion.

Db.person.batchInsert ([{"Name": "Ryan", "Age": 30},{"name": "Pitaya", "Age": 2}]);

If a document insertion fails during bulk INSERT, all documents prior to this document are inserted successfully into the collection, and the document and all subsequent document insertions fail. If you want Batchinsert to ignore the error and continue with subsequent insertions, you can use the ContinueOnError option. The shell does not support this option, but all drivers are supported.

Update:

Use the Update method to update the data in the collection. Update has four parameters and the first two parameters are required.

Db.person.update ({"Name": "Ryan"},{"$set": {"age": 35}},true,true);

First parameter: Query the document to locate the target document that needs to be updated.

The second parameter: a modifier document that describes what modifications you want to make to the found document.

The third parameter: True indicates that you want to use Upsert, that is, if a document that meets the update criteria is not found, a new document is created based on this condition and the updated document. If a matching document is found, the update is normal.

The fourth parameter: TRUE indicates that all documents that meet the criteria are updated.

modifier:

$set: Used to specify a value for a field. If this field does not exist, it is created. For updates, modify the fields that are executed for documents that meet the update criteria, and do not need to overwrite them all.

Db.person.update ({"Name": "Ryan"},{"$set": {"age": 35}},true,true);

$inc: Used to increase the value of an existing key, or if the key does not exist, create one. This can be very handy for scenes with varying values such as polls.

Db.person.update ({"Name": "Ryan"},{"$inc": {"age": 2}},true,true);//For documents that match the name equals Ryan, the Age field is added 2.

$push: Adds an element to the end of an existing array.

Db.person.update ({"Name": "Ryan"},{"$set": {"Language": ["Chinese"]}},true,true);//For documents that match the name equals Ryan, Add an array of language

Db.person.update ({"Name": "Ryan"},{"$push": {"language": "中文版"}},true,true);//Add a value to the end of the array.

$addToSet: Avoid inserting duplicate values into the array.

Db.person.update ({"Name": "Ryan"},{"$addToSet": {"language": "中文版"}},true,true);

$each: Combine with $push and $addtoset to add multiple values to the array at once.

Db.person.update ({"Name": "Ryan"},{"$push": {"language": {"$each": ["Japanese", "Portuguese"]}}},true,true );

Db.person.update ({"Name": "Ryan"},{"$addToSet": {"language": {"$each": ["Japanese", "Portuguese"]}}},true, true);

$pop: You can delete an element from either end of the array.

Db.person.update ({"Name": "Ryan"},{"$pop": {"language": 1}},true,true);//delete an element from the end of the array

Db.person.update ({"Name": "Ryan"},{"$pop": {"language": -1}},true,true);//delete an element from the head of the array

$pull: Deletes the corresponding value for the array. Delete all.

Db.person.update ({"Name": "Ryan"},{"$pull": {"language": "中文版"}},true,true);

Delete:

Use the Remove method to delete the data in the collection. It can accept a query document as an optional parameter. Given this parameter, only documents that meet the criteria can be deleted. ( delete Data is permanent, cannot be undone, and cannot be recovered ).

Db.person.remove ({"Name": "Ryan"});//delete the value of the Name field in the Person collection equals all of Ryan's documents.

Db.person.remove ();//Delete all documents in the person collection.

Using the drop method instead of the Remove method can greatly improve the speed at which data is deleted. However, this method cannot specify any qualifications. and the entire collection will be deleted, including the index and other information, very use!!

Db.person.drop ();

Inquire:

Use the Find method in MongoDB to query. The query returns a subset of the document in a collection, with a subset ranging from 0 documents to the entire collection. The Find method accepts two parameters.

The first parameter determines which documents to return, and the contents of the parameters are the criteria for the query.

The second parameter specifies the desired key (field). The second parameter exists: The value of the key is 1 for display, and 0 for the non-display. "_id" is displayed by default and other defaults are not displayed. Case where the second parameter does not exist: All fields are displayed by default.

Db.person.find ({"Name": "Ryan"},{"name": 1});

Query criteria:

$lt,$lte,$gt,$gte Four, is the entire comparison operator ( no $eq this operator ), respectively, corresponding to <, <=, >, >=.

Db.person.find ({"Age": {"$lt": 10}});

Here is a small script, insert 100,000 data, do the test after.

1  for (var i=0;i<100000;i++) {2     db.person.insert ({"Name": "Ryan" +i, "age": i}); 3 }

$in,$nin, which is used to query multiple values for a key.

Db.person.find ({"Age": {"$in": [1,3]}});//query for documents with age equal to 1 or 3.

Db.person.find ({"Age": {"$nin": [1,3]}});//query for documents with age not equal to 1 or 3.

$orthat is used to query multiple values for multiple keys. Can be used in conjunction with $in and so on.

Db.person.find ({"$or": [{"Name": "Ryan2"},{"Age": 3}]});//query name equals ryan2 or age equals 3 document.

$exists, the key of the query corresponds to a value that is null, and the default returns a document that is null and the key does not exist. The $exists can be used to determine whether the key exists.

Db.person.find ({"Age": {"$in": [null], "$exists": true}});//query Age equals NULL, and the key is a document that exists.

$where, you can use it to execute arbitrary JavaScript in the query so that you can do (almost) anything in the query. For security reasons, the use of the "$where" statement should be strictly restricted or eliminated.

Db.person.find ({"$where": function () {

...;//This can be any JavaScript statement.

}})

cursors : Cursors can be used to limit the number of results, to skip partial results, to sort the results by any combination of any key, or to perform other powerful operations.

1 var cursor = db.person.find (); 2  while (Cursor.hasnext ()) {3     obj = cursor.next (); 4     ...; // you can do everything here.   5 }

Common shell:

Limit: Returns only the previous number of results.

Db.person.find (). Limit (2);//query a document that matches the criteria, showing the first two documents.

Skip: Shows the remaining after how many results have been skipped.

Db.person.find (). Skip (2);//query a document that matches the criteria, showing all documents remaining after skipping 2 documents.

Sort: used for sorting. Takes an object (a set of key-value pairs) as an argument, and the key corresponds to the key name of the document, and the value represents the direction of the sort. The direction of the sort can be 1 (ascending) or-1 (descending). If more than one key is specified, the keys are sorted in the order specified.

Db.person.find (). Sort ({"Name": 1, "Age":-1});//The result of the query, sorted by name ascending, age descending.

Play to MongoDB (iv): Elaborate insert, UPDATE, delete, and query

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.