About MongoDB
MongoDB is lighter and more flexible than some relational databases, and is ideal for use in situations where data is large and transactional is not strong. It is also an object database with no concepts such as tables, rows, or fixed patterns and structures, and all data is stored as documents.
• Written by the C + + language, is an open source NoSQL database system for Distributed file storage. In the case of high load, adding more nodes can guarantee the performance of the server.
· MongoDB is designed to provide scalable, high-performance data storage solutions for Web applications
· MongoDB stores data as a document and data structures consist of key-value pairs. MongoDB documents are similar to JSON objects, and field values can contain other documents, arrays, and document arrays.
Install https:www.mongodb.org/download Download the installation package
Installation of visual tools such as Robomongo, Mongovue, etc.
MongoDB start-Up and connection
-Windows boot server to find the MongoDB installation directory (such as D:\mongodb), shift+ right-click to open the Command window, create a new data folder, on the command line to enter
Mongod--dbpath=d:\mongodb\data
If connections on port 27017 is present, the boot succeeds and the client's request is monitored on port 27017. The value after--dbpath represents the storage path of the database file, and the subsequent path must be created beforehand, must already exist, or the service fails to open. In addition, once the command form is closed it is tantamount to stopping the service of MongoDB.
-Start the Client Connection server to find the MongoDB installation directory, such as D:\mongodb\bin, open the Command line window in this directory, enter MONGO--host=127.0.0.1 or MONGO, press ENTER, Where the value after--host represents the IP address of the server, 127.0.0.1 represents the local server, each time the database is connected by default to the test database
MongoDB Basic Concept
• Database
1, a MongoDB can build multiple databases
A single instance of 2,mongodb can hold multiple independent databases, each with its own collection and permissions, and different databases placed in different files.
3, the database is also identified by name, the database name can be any UTF8 string that satisfies the condition
-cannot be an empty string
-Cannot contain spaces 、.、 $,/, \, and (null characters)
-Should all lowercase
-Up to 64 bytes
4, some database names are reserved and can be accessed directly to these special-purpose databases
-admin: ' Root ' database, if you add a user to this database, the user will automatically inherit all the database permissions, and some specific server-side commands can only be run from this database, such as listing all databases or shutting down the server
-Local: This database is never replicated and can be used to store any set of local single servers
-Config: When MongoDB is used for sharding settings, the Config database is used internally to hold information about the Shard
• Document (equivalent to row)
A document is a core unit in MongoDB that can be likened to each row of data in a relational database. Multiple keys and their associated values are placed together in an orderly manner as documents. MongoDB uses the Bson structure to store data and network data exchange. Bson data can be understood to add some data types that are not in JSON, based on JSON.
• Collection (equivalent to table)
A collection is a combination of a set of documents that can be likened to a database table if the document is likened to a row in a database. The collection in MongoDB is modeless, which means that the structure of the document stored in the collection can be different, such as the following two documents can be deposited into a collection at the same time
{"Name": "Lucy"} {"Name": "Lily", "Sex": "Female"} Note: When the first document is inserted, the collection is created
• Fields field (equivalent to column)
Basic operations on MongoDB
Methods of the database Help
• CREATE DATABASE use database_name NOTE: If the database does not exist, create the database, or switch to the specified database
• View all databases Show DBS NOTE: If a new database is not displayed, you will need to insert some data into the new database Db.collection_name.insert ({name: ' Zhangsan '})
• View the currently used DB or db.getname () Note: DB represents the current database
• Delete Database Db.dropdatabase ()
• Disconnect MongoDB from MongoDB service exit
Action Collection Method Db.worker.help () View Help API
• See which collections are in the current database show collections
• Create collection Db.createcollection ("collection_name")
• Inserting a document into the collection Db.collection_name.insert Note: Document refers to the documents to be inserted
• See how many document data are in the collection Db.collection_name.count ()
• Delete the collection in the current database Db.collection_name.drop ()
Methods of documentation
• Inserting document Db.collection_name.insert will automatically generate a _id number when the document is inserted, and the _id type is Objectid type.
Multiple documents can also be inserted into the collection at once using an array Db.collection_name.insert ([Document1,document2])
• Query all documents in the collection Db.collection_name find ()
• Insert the document using the Save method (insert or update), _id if it exists, _id if it does not exist. Usage is similar to insert
• Update documents that already exist Db.collection_name.update (<query>,<update>,{upsert:<boolean>,multi:<boolean> , Writeconcern:<document>})
-query:update query condition, similar to where in SQL update query
-Update:update objects and some updated operators (such as $set, $inc ... ), $inc updated on the basis of the original, $set directly updated
-Multi: Optional, default false, update only the first record found, or true to update multiple records on a condition-by-case basis
Eg:db.worker.update ({name: ' Zhangsan '},{$set: {name: ' zhangsan123 '}})
Extended
Each document stored in the MongoDB collection has a default primary key _id, which is fixed and can be any data type supported by MongoDB, which is objectid by default. The value of this type is generated by the system itself and is not duplicated in a sense. The primary keys for relational databases such as MySQL are self-increasing. However, in a distributed environment, this approach is not feasible and can create conflicts. Therefore, MongoDB uses the Objectid type to master the key. Objectid is a 12-byte Bson type string.
Mongoose
Mongoose is an object model tool for MongoDB and is a NODEJS driver based on node-mongodb-native developed by MongoDB, which can be executed in an asynchronous environment. At the same time, it is also an object model library for MongoDB operations, which encapsulates some common methods such as MongoDB's addition and deletion of documents, and makes it easier for Nodejs to manipulate MongoDB database.
• Installation Mongoose
NPM Install Mongoose
• Reference Mongoose
var mongoose = require (' Mongoose ')
• Connect to the database using Mongoose
var db = Mongoose.connect (' mongodb://user:[email protected]:p ort/database ')
• Perform the following code to check the default database test for proper connection success
// 2 load module
var mongoose = require ("mongoose");
// 3. Connect to the database mongod server mongo client
// The name of the database may not exist Create a zf database
var db = mongoose.connect ("mongodb: //123.57.143.189: 27017 / zf");
// If the connection is successful, an error callback will be executed
db.connection.on ("error", function (error) {
console.log ("Database connection failed:" + error);
});
// If the connection is successful, open callback will be executed
db.connection.on ("open", function () {
console.log ("Database connection succeeded");
});
// Define a schema describing what fields are in this collection and what type of fields
// Only the attributes in the schema can be saved to the database
var PersonSchema = new mongoose.Schema ({
name: {type: String},
home: {type: String},
age: {type: Number, default: 0},
time: {type: Date, default: Date.now},
email: {type: String, default: ‘‘}
});
// Create a model that can be used to manipulate the person collection in the database, referring to the whole
var PersonModel = db.model ("person", PersonSchema);
// Create entities based on models, referring to individual objects
var personEntity = new PersonModel ({
name: "zf",
age: 6,
email: "[email protected]",
home: 'beijing'
});
// Save yourself to the database with the save method
personEntity.save (function (error, doc) {
if (error) {
console.log ("error:" + error);
} else {
console.log (doc);
}
});
The schema (data attribute model), model, Entity should be used if you want to create a collection by Mongoose.
Schema Brief
This is a file-based database model skeleton, not directly to the database side, that is, it does not have the ability to operate the database, just a database model in the program fragment of a performance, can be described as a data attribute model (traditional meaning table structure), or a set of model skeleton. The basic attribute types are string, date, numeric, Boolean, NULL, array, inline document, and so on.
Define a schema:
var PersonSchema = new monoose.Schema({
name:{type:String},
age:{type:Number,default:0} ,
time:{type:Date,default:Date.now},
email:{type:String,default:‘‘}
})
Model Brief
The model generated by the schema construct, in addition to the database skeleton defined by the schema, has the behavior of database operations, similar to the classes that manage data properties and behaviors.
Create model from Schema
// Create a model that can be used to manipulate the person collection in the database, referring to the whole. Create a person collection
var PersonModel = db.model ("person", PersonSchema);
Person: The collection name in the database, when we add data to it, if the person already exists, it is saved to its directory, and if it does not exist, the person collection is created, and then the data is saved. With the model, there is the ability to manipulate the data. To create a model, you need to specify two points: 1, the collection name, 2, the schema structure object of the collection. Meet these two points, you can operate the database.
Entity Brief
Entities created by model use the Save method to save data, both model and entity have operations that affect the database, but the model is more operational than entity. Once the entity is created, the schema property becomes the public property of model and entity.
Creating an entity Using Model
// Create entities based on models, referring to individual objects
var personEntity = new PersonModel ({
name: "zf",
age: 6,
email: "[email protected]",
home: 'beijing'
});
Mongoose Basic Operations
• Enquiry
Queries are categorized into multiple types, such as conditional queries, filter queries, and so on. Obj.find (query condition, field,callback), field is omitted or NULL, all properties are returned, field shows the property that needs to be displayed to a number greater than 0 returns the property, _id does not specify a default return, and setting _id to 0 does not return the property. The other fields are not specified and are not returned by default
Model.find ((), function (error, docs) {
// If no parameters are passed to find, the default is to display all documents
})
The query returns a subset of the files in a collection, and the Mongoose model provides the find, FindOne, and FindByID methods for document queries
FindOne query a single, when the query to a qualifying data, will stop the query and return the results of the query.
// Create a model that can be used to manipulate the person collection in the database, referring to the whole
var PersonModel = db.model ("person", PersonSchema);
// Specify the returned field 1 means to return 0 without returning,
// If the field is not specified, it will not be returned by default.
// _ id will be returned if not specified, if you don't want him to return, you need to specify 0 explicitly
PersonModel.find ((), {name: 1, age: 1, _id: 0}, function (err, docs) {
console.log (docs);
})
// When the first matching record is found, return immediately, no further searching, return a single object
PersonModel.findOne ({name: / ^ \ w + 9 $ /}, {name: 1, age: 1, _id: 0}, function (err, doc) {
console.log (doc);
})
// Query by ID
PersonModel.findById (‘56ee117356acb568054dd6d4’, {name: 1, age: 1, _id: 0}, function (err, doc) {
console.log (doc);
})
-Advanced Enquiry
Query for exclusions using $GT (>), $lt (<), $lte (<=), $gte (>=), $ne (Not Equal), $in (included), $or (or), $exists (presence) operator
// Create a model that can be used to manipulate the person collection in the database, referring to the whole
var PersonModel = db.model ("person", PersonSchema);
PersonModel.find ({‘age‘: {"$ gt": 6}}, {name: 1, age: 1, _id: 0}, function (err, docs) {
// Query data with age> 6
console.log (docs);
})
PersonModel.find ({‘age‘: {"$ gt": 6, "$ lt": 9}}, {name: 1, age: 1, _id: 0}, function (err, docs) {
// Query 6 <age <9 data
console.log (docs);
})
PersonModel.find ({"name": {"$ ne": "zf"}, 'age': {"$ gt": 6, "$ lt": 9}}, {name: 1, age: 1, _id: 0}, function (err, docs) {
// Query the data of name! = ‘Zf’ && 6 <age <9
console.log (docs);
})
PersonModel.find ({"name": {"$ in": "zf"}}, {name: 1, age: 1, _id: 0}, function (err, docs) {
// Query all data with name == ‘zf’
console.log (docs);
})
PersonModel.find ({"age": {"$ in": [6,7]}}, {name: 1, age: 1, _id: 0}, function (err, docs) {
// Query all data of age == 6 or 7
console.log (docs);
})
PersonModel.find ({age: {$ in: 6}}, function (error, docs) {
// Query all data with age equal to 6
console.log (docs);
});
PersonModel.find ({age: {$ in: [6,10000]}}, function (error, docs) {
// Can organize multiple values into an array
console.log (docs);
});
PersonModel.find ({email: ‘email’, "$ or": [{"name": "zfpx1"}, {"age": 2000}]}, function (error, docs) {
// Query all documents with name zfpx or age 6.
console.log (docs);
});
var start = new Date ();
var end = new Date ();
PersonModel.find ({time: {$ lt: end}, time: {$ gt: start}}, function (error, docs) {
// Query all documents with name zfpx or age 6.
console.log (docs);
});
-Cursor operation
The database uses cursors to return the results of find execution, and the client's implementation of the cursor usually provides effective control over the final result. You can limit the number of results, skip some of the results, sort the results by any combination of keys, or other operations. The most common query options are limiting the number of returned results (limit function), ignoring a small number of results (skip function), and sorting (sort function). All of these options must be specified before the query is sent to the server.
The basic usage of the-LIMIT function in query operations, sometimes the amount of data is very large, then we need to limit the number of returned results, you can use the limit function to limit the number of results
PersonModel.find({name:/zf/},null,{limit:10},function(err,docs){
console.log(docs);
});
The basic usage of the-SKIP function is similar to the limit, which operates on the number of returned results, but the function of the skip function is to skip the specified number of matching results and return the remaining query results
The basic usage of the-sort function sorts the query result, which is one or more key-value pairs, the key represents the key name to sort, the value represents the direction of the sort, the 1 is ascending, and 1 is the descending
// Now you want to query by pages, 3 items per page, query page 2
// skip the number of skipped limit limit the number of returned sort sort 1 ascending order -1 descending order will be sorted before skip, then limit
PersonModel.find ((), {_ id: 0, name: 1}, {limit: 3, skip: 3, sort: {age: 1, name: -1}}, function (err, docs) {
console.log (docs);
});
• Save
-model provides a create method to save the data. Model.create (document data, callback)
// Insert 10 documents into the collection
for (var i = 1; i <= 10; i ++) {
// Save the document in the data
PersonModel.create ({name: ‘zfpx‘ + i, age: i}, function (err, doc) {
if (err) console.log (err);
else
console.log (doc); // doci
});
// All asynchronous methods are executed after all synchronous methods have been executed
console.log (i);
}
-entity provides a save method for saving data. Entity.save (document data, callback)
// Create entities based on models, referring to individual objects
var personEntity = new PersonModel ({
name: "zf",
age: 6,
email: "[email protected]",
home: 'beijing'
});
// Save yourself to the database with the save method
personEntity.save (function (error, doc) {
if (error) {
console.log ("error:" + error);
} else {
console.log (doc);
}
});
• Data Updates
Model.update (query condition, update object, callback) updates a document by default, and if you want to update it all, you need to add {multi:true}
// Create a model that can be used to manipulate the person collection in the database, referring to the whole
var PersonModel = db.model ("person", PersonSchema);
// $ set updater specifies the fields to update
var update = ($ set: {age: 100});
// Update
// multi update all records that match
PersonModel.update ({name: ‘zf‘}, update, {multi: true}, function (error) {
if (error) {
console.log (error);
} else {
console.log (‘Update success!’);
}
});
• Data deletion model.remove (query conditions, callback)
PersonModel.remove({name:‘zf‘},function(err,docs){
//result: { ok: 1, n: 3 }
console.log(docs);
});
[Goto] MongoDB and Mongoose