MongoDB + Node-mongoskin Learning Notes

Source: Internet
Author: User
Tags findone

Characteristics
Every document in a modeless MongoDB is a JSON object, so you don't have to predefine the structure of a collection, and each document in the collection can have a different structure.

Asynchronously writes to MongoDB by default all writes are "unsafe", that is, when a request is received by MongoDB, the write operation is completed and a "successful" response is returned. This is the default behavior, and of course you set some options so that the operation waits for the write to complete before returning the response. For most applications, however, this "unsafe" is safe enough.

Simple query MongoDB only supports simple queries, MongoDB only stores data, more logic should be resolved in the application. MongoDB therefore has a simple and highly consistent API interface in each programming language.

There are few options to set up without operations MongoDB, and a cluster can be set up once and then automatically to resolve failures, requiring minimal maintenance.

Install and backup run Mongod start the database, run MONGO to start the client Shell.

MongoDB is designed to operate on a 64bit operating system, and in 32bit cases the maximum data file limit is 2GiB.


MongoDB does not write changes to disk in real time at run time, so you need to write all the data to the disk when you shut down the server. When the server suddenly loses power, MongoDB database files will be damaged and need to be repaired to re-run, this process will lose the power when the write operation. When you back up a running MongoDB, you need to use your own mongodump tool and not replicate its database files directly.



Design document Structure
Objectidmongodb will add a field named _id, type Object, to each document by default, and this field is used to uniquely identify each document. This ID is generated by time, server, process number, and can even be considered to be the only one in the world.
In addition to MongoDB by default adding ObjectID to _id, you can also create your own ObjectID in the document to uniquely identify an object's functionality.

Query and update the so-called "additions and deletions" in MongoDB correspondence:
Find/findone: Query
Update/save: Modify
Insert/save: New
Remove: Delete

In MongoDB, the operator begins with $ and is divided into three main categories: The query operator, the update operator, and the aggregate query operator.

Query operators are used for queries in find and update, such as $GT (greater than), $ne (not equal to), $in (matches one of several values), logical operations: $and, $not.

The update operator is used for updates in the update, such as $inc (increment the number), $set (modify part of the document), $unset (delete a field).
MongoDB has very good support for embedded documents and arrays: $addToSet (adding elements to the collection), $push (adding elements to an array), $pull (removing elements from an array).

Aggregate queries (Aggregation) are similar to the GROUP in SQL databases, providing statistical and computational capabilities that are powerful enough to run JavaScript code directly in the database, but because of the performance of the relationship, it is not suitable to be called frequently in the application.

There are several options for the query command limit: Limits the number of results returned
Skip: Skip Some results
Sort: Sorting the results
Fields: Returns only the specified field



MongoDB can conveniently put some of the data that MySQL needs to be associated with a one-to-many relationship through an array + object as a document stored in a collections, and provides various APIs to support the operation of an array within a document.

MongoDB Common Query method and its embodiment in node:


1. Database connection mongodb:mongo-u username-p password Host:port/dbs
Node+mongoskin:require ("Mongoskin"). db (Username:[email protected]:p Ort/dbs);

2. Index

Person.ensureindex ({"Name": 1},{"unique": true}, callback);

The first parameter is selector, the second parameter is the option, and the MONGODB index option is unique (unique index).
Ensureindex first looks for the existence of the index, and if it does not exist, the index is established, so there will be no duplicate builds.

3. New/Added data Person.save ({"Name": "Jobs", age:32, Gender: "Male"}, callback);
Person.save ({"Name": "Tim", age:29, Gender: "Male"}, callback);

Db. Collection name. Insert ({name: ' Xiaoxiao ', age:2},function (Error,result) {}

4. Enquiry

FindOne method: Query conforms to the results of the selector condition, take the first to Callback,err is the error message, if there is no error, then the Undefined,data data is a JS object.

Person.findone ({"Name": "Jobs"}), CallBack (err, data));

Find method: The query conforms to the selector condition, and can also add a series of parameters, and finally through the ToArray method, the data generation array way to callback.
Person.find ({"Gender": "Male"},{sort:[[' name ', 1]],skip:pagenum* (page-1), limit:pagenum}). ToArray (Callback (Err, Data) {});
At the same time can be queried by $in, $GT, $lt and other ways to determine the scope of selector.

$ne: Not equal;
Personcollection.find ({age:{$ne: ' 2 '}},function (error,result) {}
$in: Whether a value is specified in this range, followed by a general array of ranges, the type of the value of the array can be different;
Personcollection.find ({age:{$in: [' 2 ', ' 3 ', ' 4 ', ' 5 ']}},function (error,result) {}
$nin: Indicates that it is not in an array range;
Personcollection.find ({age:{$lte: ' 3 '}},function (error,result) {}
$lt, $lte, $GT, $gte: Represent &lt respectively, <=,>, >=, which are used to set the query scope;
$or: also specifies a range to use, but the biggest difference from the above is that $in, $nin have only one array range, and $or can be multiple array range to meet the conditions;
Personcollection.find ({$or: [{name: ' King two '},{age: ' 2 '}]},function (error,result) {}

5. Update

There are two points to note:

[1], Update method if you want to update one or several properties in the document, you must use the form {$set: {age:33}}, if written as {age:33}, then the other contents of this document will be deleted, only {age:32} this one property.
[2], the Update method by default is only the first document found to update, if you need to update all the documents, you need to add {multi:true} in the option section, if you want to find this record when a new one, you want to add {upsert in the option section: True}.
Person.update ({"Name": "Jobs"}, {$set {"Age": +}}, {multi:true}, callback (ERR))
[3], $inc by step increments, such as the age field to increase by 1.
Personcollection.findandmodify ({_id: ' 1111111 '},[],{$inc: {age:1}},{new:true,upset:true},function (Error,result) { }

6. Delete

Person.remove ({"Name": "Jobs"},callback (err) {});


7. Automatically generated _IDMONGODB using MongoDB in selector generates a _id attribute for each document, similar to MySQL's primary key, which is unique. The type of _id is MongoDB's own defined objectid type, so although a 12-bit or 24-bit _id string can be obtained at query time, if you want to search through _id in selector or other operations, You must first type-convert through the Db.collection.id () method.
Person.remove ({"_id":p erson.id (Stringid)}, callback (ERR) {});

8, MongoDB operation of the array in the document (through the Update method) [1], through the $addtoset method to insert records into the array, before inserting the method will first look for the existence of this record, if there is not inserted, if you want to insert a duplicate value, you can pass the Push to Add.
Person.update ({"Name": "Jobs"}, {$addToSet: {
Company: {
Name: "Google",
Address:usa,
Workingtime:3
}
}, function (Err) {});

[2], modify the data in the array: by the $ character. If the query in the array to match two attributes, you must use the $elemmatch method, if only through {"name": "Google", "Address": "USA" to find, will be selected to all the name of Google or address for the USA element. After you navigate to this element, select it by $ to modify it.
Person.update ({
"Name": "Jobs",
company:{$elemMatch: {"name": "Google", "Address": USA}}
}, {$set: {"Company.$.workingtime": 4}},function () {})

[3], delete the data specified in the array: through the $pull method
Person.update ({
"Name": "Jobs",
},{$pull: {company:{"name": "Google", "Address": "USA"}}},function (err) {})

$pop: Delete the array header or tail to delete a value {$pop: {filed:-1}} from the beginning, {$pop: {filed:1}} from the tail.
Personcollection.findandmodify ({_id: ' 1111111 '},[],{$pop: {tag:-1}},{new:true,upset:true},function (Error,result) {}

Reference http://jysperm.me/technology/1575
Http://www.cppblog.com/dead-horse/archive/2011/09/23/156617.html

Https://github.com/kissjs/node-mongoskin




Document Information

    • Copyright Disclaimer: Free Reprint-Non-commercial-non-derivative-retain attribution | Creative Commons by-nc-nd 3.0
    • Original URL: http://blog.csdn.net/cdztop/article/details/31324027
    • Last modified: June 16, 2014 06:32
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.