Mongodb

Source: Internet
Author: User

Tags: stop key value pair OLE JSON free collection need attention NEC

MongoDB is a non-relational database, NoSQL, and does not require the use of SQL statements

In the rookie tutorial, MongoDB stores data as a document, data structures consist of key-value pairs, and documents are similar to JSON objects

The database is also called a database in MongoDB, but the data table is called a collection (array), the table data is called a document

The whole MongoDB can be regarded as a large object, which stores objects (databases), objects stored in groups (collections), the array can only save objects, a record is an object, and the object can save any type of data

MONGODB document structure is flexible without any restrictions, do not need to create a database, table, design table structure like MySQL, need to insert data need to specify which database to which the collection operation, all by MongoDB to help automate the building of the library table

Installation

Download Community Edition (Community Server) as free

The default is C drive, the installation path is C:\Program Files\mongodb, after installation will be configured to the bin directory path to the environment variable path

The purpose of configuring an environment variable is to use its executable file under each drive letter, otherwise it can only be used in its bin directoryafter that, you can use the command Mongod--version to see if the version check was successfully installed.

Start

MongoDB is not like MySQL can be started in the Control Panel service, how to want to start in the service, you can go to the novice to view the tutorial

Another way to start is the command line execution mongod command, which defaults to using data/db as its own data store directory under the root directory of the disk.

If the DOS window opened in the C-drive, it will be stored in the C-packing directory of the data/db, the other disk to run the command must first manually at the current disk root directory to create data/db

is the C packing directory, no data/db.

Start the database successfully by manually creating the data/db and then executing the mongod command

To change the default data store command, you can run

Mongod--dbpath= data Store directory path

Stop it

Close the current DOS window or Ctrl + C directly

Connection

Do not close the console after the execution of Mongod , and then open a new DOS window, execute MONGO , the command will default to connect to the local MongoDB service, exit the words in the connection state using the Exit command

Note that if the database is not open (that is, the Mongod command is not executed), it cannot be connected.

Command

Show DBS command to display all databases

The DB command looks at the database of the current operation, by default in the test database, because test has no data at this time, so the show DBS command does not show test

The use database name command is used to switch to the specified database (no new ones are created), no data, and therefore does not appear

After use, the DB at this point represents the student database

Manipulating MongoDB in Node

The official mongodb native package is not easy to operate, so it is common to use third-party Mongoose to manipulate MongoDB

Mongoose is based on the official MongoDB package once again made the package

Usage,NPM is downloaded and loaded in code with request ().

Mongoose website with examples and use of documents

After executing the example above, you can query to the test database with the Cats collection

An example explanation

varMongoose = require (' Mongoose '))varSchema =Mongoose. Schema//1. Connect to the database//connect to the native test database, MongoDB is dynamic, the specified database does not need to exist, insert a piece of data will be automatically createdMongoose.connect (' Mongodb://localhost/test ')//2. Design document structure (table structure)//The field name is the name of the property in the table structure and can be constrainedvarUserschema =NewSchema ({username:{type:string,//username field, type is field data typeRequiredtrue //Add a constraint that indicates that the username field cannot be empty}, password:{type:string, required:true}, Age:number})//3. Publish the document structure as a model/*The first argument is passed in an uppercase noun singular string to represent the data table name, and mongoose automatically generates the uppercase noun string with the collection name of the lowercase plural users The second parameter is schema schemas, and the custom table structure return value is the model constructor*/varuser = Mongoose.model (' user ', Userschema)//4. Once you have the model constructor, you can use this constructor to manipulate the Users collectionvaruser =NewUser ({username:' Admin ', Password:' 123456 ', Age:18})//5. Persist the storage, start the server first, data is the insertedUser.save (function(err,data) {if(Err) {Console.log (' Save Failed ')    }Else{Console.log (' Save Success ')    }})

MongoDB automatically helps set the ID field (field name is _id ), so you don't have to manually set the Id,id to be a string and enclose it in double quotes.

Querying data

In addition to adding the data is to create a new object user, the other user calling method is returned directly using Mongoose.model (' User ', Userschema)

//queries all the data in the collection, returns an arrayUser. Find (function(err,data) {if(Err) {Console.log (' Query failed ')    }Else{console.log (data)}})//according to the criteria query, query username for the admin data, there are multiple conditions to continue to write on canUser.find ({username:' Admin '},function(Err,data) {})//The object is returned by a conditional query. Returns the first record if the condition is not written. also FindByID () queries the object by IDUser.findone ({username:' Admin '},function(Err,data) {})

Delete data

// Delete all eligible data, plus multiple conditions user.remove ({    username:' admin '},function  (err,data) {    if (Err) {        console.log (' delete failed ')    }}) //Delete one according to the conditions: Findoneandremove (Conditions,[options],[callback])
Delete one by ID: Findbyidandremove (id,[options],[callback])

Update data

// Update data based on ID, ID, content to update, callback User.findbyidandupdate (' 1001 ', {    password:' 123 '}),function  (err,data) {     if(err) {        console.log (' update failed ')    }}// Update one according to specified criteria: findoneandupdate ([Conditoins],[update],[callback])

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.

Tags Index: