MongoDB + node-Skip skin Study Notes

Source: Internet
Author: User
Tags findone mongodb query

Features
Every document in the schema-free MongoDB is a JSON object. Therefore, you do not need to predefine the structure of a set. Each document in the set can have a different structure.

By default, all write operations for asynchronous writing to MongoDB are "insecure". That is, when the request is received by MongoDB, a "success" response is returned when the write operation is complete. This is the default action. Of course, you can set some options to wait for the Operation to return a response after the write is completed. However, for most applications, this kind of "insecure" is safe enough.

Simple query MongoDB only supports simple query, MongoDB only stores data, and more logic should be solved in the application. Therefore, MongoDB has simple and highly consistent API interfaces in different programming languages.

There is almost no option to configure MongoDB without O & M, and the cluster can automatically solve the fault once it is set, with minimal maintenance required.

Install and back up mongod to start the database and run mongo to start the client Shell ,.

MongoDB is designed to run on 64-bit operating systems. In 32-bit cases, the maximum data file size is 2 Gib.


MongoDB does not write modifications to the disk in real time during runtime. Therefore, when you shut down the server, you need to write all data to the disk for MongoDB. When the server suddenly loses power, the MongoDB database file will be damaged and need to be repaired before it can be re-run. In this process, the write operation in progress will be lost when power loss occurs. When backing up a running MongoDB instance, you must use the built-in mongodump tool to copy its database files.



Design document structure
ObjectIDMongoDB adds an Object field named _ id for each document by default. This field uniquely identifies each document. This ID is generated by time, server, and process number, and can even be regarded as the only one in the world.
Besides adding ObjectID to MongoDB by default, you can also create ObjectID in the document to uniquely identify an object.

The so-called "add, delete, query, and modify" query and update are matched in MongoDB:
Find/findOne: Query
Update/save: Modify
Insert/save: New
Remove: Delete

In MongoDB, operators starting with $ are classified into three types: Query operators, update operators, and aggregate query operators.

The query operator is used in the find and update queryers, such as $ gt (greater than), $ ne (not equal to), $ in (matching one of several values), and the logical operation is: $ and, $ not.

The update operator is used to update the Updater, for example, $ inc (increment the number), $ set (modify part of the document), and $ unset (delete a field ).
MongoDB provides excellent support for embedded documents and arrays: $ addToSet (adding elements to the Set), $ push (adding elements to the array), and $ pull (removing elements from the array ).

Aggregate Query (Aggregation) is similar to a GROUP in an SQL database. It provides statistics and computing functions. It must be strong, strong, and powerful. After all, JavaScript code can be run directly in the database. However, due to performance, it is not suitable for frequent calls in applications.

The query command also has several options: limit the number of returned results
Skip: skip some results
Sort: sorts the results.
Fields: only the specified field is returned.



MongoDB can easily store data that MySQL needs to associate with one-to-many relationships into a Collections using arrays and objects as a document, various APIs are provided to support operations on arrays in a document.

Common MongoDB query methods and their embodiment in node:


1. Database Connection MongoDB: mongo-u username-p password host: port/dbs
Node + login skin: require ("login skin"). db (username: password @ host: port/dbs );

2. Index

Person. ensureIndex ({"name": 1}, {"unique": true}, callback );

The first parameter is selector, and the second parameter is option. It has mongoDB index options such as unique (unique index.
EnsureIndex first checks whether this index exists. If it does not exist, an index is created, so it will not be created again.

3. Create/add data person. save ({"name": "jobs", age: 32, gender: "male"}, callback );
Person. save ({"name": "tim", age: 29, gender: "male"}, callback );

Db. Set name. insert ({name: 'xiaoxiao', age: 2}, function (error, result ){}

4. Query

FindOne method: query the result that meets the selector condition and obtain the first one to callBack. err is the error message. If there is no error, it is undefined. data is a JS object.

Person. findOne ({"name": "jobs"}), callBack (err, data ));

Find method: the query meets the selector condition, and a series of parameters can be added. Finally, the toArray method is used to pass the data generation array to callback.
Person. find ({"gender": "male"}, {sort: [['name', 1], skip: pageNum * (page-1), limit: pageNum }). toArray (callback (err, data ){});
You can use $ in, $ gt, and $ lt to determine the selector range during query.

$ Ne: not equal;
PersonCollection. find ({age: {$ ne: '2'}, function (error, result ){}
$ In: whether a value is in the specified range. Generally, a range array is specified. The type of the nominal value in the array can be different;
PersonCollection. find ({age: {$ in: ['2', '3', '4', '5'] }}, function (error, result ){}
$ Nin: indicates that it is not in the range of an array;
PersonCollection. find ({age: {$ lte: '3' }}, function (error, result ){}
$ Lt, $ lte, $ gt, and $ gte represent <, <=,>, >=, respectively. They are used to set the query range;
$ Or: specifies a range, but the biggest difference is that $ in and $ nin have only one array range, while $ or can meet the conditions in multiple array ranges;
PersonCollection. find ({$ or: [{name: 'wang erxiao '}, {age: '2'}]}, function (error, result ){}

5. Update

Note the following two points:

[1] If the update method is to update one or more attributes in the document, it must be in the form of {$ set: {age: 33, if it is written in the form of {age: 33}, other content in this document will be deleted, with only the attribute {age: 32} left.
[2]. By default, the update method only updates the first document found. to update all documents, add {multi: true} to the option section }, if you want to add a new record when you cannot find it, add {upsert: true} to the option section }.
Person. update ({"name": "jobs"}, {$ set {"age": 33 }}, {multi: true}, callback (err ))
[3] and $ inc increase by step. For example, add 1 to the age field.
PersonCollection. findAndModify ({_ id: '000000'}, [], {$ inc: {age: 1 }}, {new: true, upset: true}, function (error, result ){}

6. Delete

Person. remove ({"name": "jobs"}, callback (err ){});


7. Using the _ idMongoDB automatically generated by MongoDB in selector generates a _ id attribute for each document, which is similar to the primary key of MySQL and is unique. The _ id type is the objectID type defined by mongoDB. Therefore, you can obtain a 12-or 24-bit _ id string during query, however, if you want to use _ id in selector for search or other operations, you must first use db. collection. id () method for type conversion.
Person. remove ({"_ id": person. id (stringID)}, callback (err ){});

8. mongoDB operates on arrays in the document (using the update method) [1]. It inserts records into the array using the $ addToSet method, before insertion, this method will first check whether this record exists. If yes, it will not be inserted. If you want to insert duplicate values, you can add them through $ push.
Person. update ({"name": "jobs"}, {$ addToSet :{
Company :{
Name: "google ",
Address: USA,
WorkingTime: 3
}
}, Function (err ){});

[2]. Modify the data in the array: use the $ character. If you want to match two attributes in an array, you must use the $ elemMatch method. If you only search for these attributes by {"name": "google", "address": USA, all elements whose names are google or whose addresses are USA will be selected. After locating this element, select it through $ to modify it.
Person. update ({
"Name": "jobs ",
Company: {$ elemMatch: {"name": "google", "address": USA }}
},{$ Set: {"company. $. workingTime": 4 }}, function (){})

[3]. Delete the specified data in the array: use the $ pull method.
Person. update ({
"Name": "jobs ",
},{$ Pull: {company: {"name": "google", "address": "USA" }}, function (err ){})

$ Pop: delete an array header or tail value {$ pop: {filed:-1} from the beginning, and delete {$ pop: {filed: 1} from the end.
PersonCollection. findAndModify ({_ id: '000000'}, [], {$ 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 statement: Free Reprint-non commercial-Non derivative-keep the signature | Creative Commons BY-NC-ND 3.0
  • Http://blog.csdn.net/cdztop/article/details/31324027
  • Last modification time: June 16, 2014

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.