Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

MongoDB tutorial

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

I. installation

Then configure the environment variable, find the bin directory, copy the path, create a new one under path, and then enter the copy directory to make sure.

Configure the "environment variable" to be used directly on the command line without having to enter a long path into the installation directory to use it.

1. Open the terminal, type mongod, and start the MongoDB server

2. The error occurs because there is no data\ db folder under C:\ directory. The solution is to create a new data folder under C disk, and then create a new db folder under data, because the default database directory for MongoDB in Windows is c:\ data. If you run mongod directly without this directory, an error will be reported.

3. But we can change the database directory

Mongod-- dbpath=D:\ wonderful classroom folder\ 190122Nodejs develop blog system\ db-- port=27017

-- dbpath is the specified database storage directory

-- port refers to the database port number

4. Re-enter mongod to start the MongoDB server. The default port is 27017

5. After successfully starting the MongoDB server, open a command line window to enter mongo, connect to the database, and then you can do some database operations.

Show dbs: view existing databases

Db.version (): check the database version show users: show the user use admin: enter the admin database, and now you can use the library (if there is no library, the library will be automatically created). If there is no data under the newly created library, the library will not be displayed by default. Show collections: view all the collections under the database db: check which database you are currently under, or which database you are currently using

Second, the difference between MongoDB and relational database.

For example: mysql table tables, MongoDB here is called set collections, and each piece of data in the collection is called document.

MongoDB is a non-relational database that stores data as a document, and the data structure consists of key-value pairs. MongoDB documents are similar to JSON objects in that field values can contain other documents, arrays, and document arrays.

One mongoDB can build multiple databases.

Create a database, insert data, and view data

Use user / / create a new database

Db.user.insert ({"name": "xiao"}) / / add a piece of data

Db.user.find () / / View all the data

Db.user.findOne () / / display the first piece of data

Db.user.update ({"name": "xiao"}, {"name": "kate", "age": "18"}) / / modify the data

Db.user.remove ({"name": "xiao"}) / / Delete data

4. Write mongo commands with js file

/ / insert the user name and login time into the log library. Through the goTask.js operation, variables are defined using var, do not use letvar userName= "jspang"; / / declare a login name var timeStamp=Date.parse (new Date ()); / / declare the login timestamp var jsonDdatabase= {"loginUnser": userName, "loginTime": timeStamp}; / / constitute the JSON string var db = connect ('log') / / Link the database, use use log on the command line, use connect ('log') in the js file, and no creation library db.login.insert (jsonDdatabase); / / insert data print (' [demo] log print success'); / / No error shows success / / execution file, command line: mongo goTask.js

5. Batch insertion

There are two abilities to pay attention to when operating a database:

The first is fast storage capacity.

The second is the ability to query conveniently and quickly.

Be careful not to insert more than 48m at a time. Insert .zip and large images as static storage as possible. MongoDB can store static paths. This is also a rule.

If you can't hold it up in loops and bulk inserts at work, choose bulk inserts, which will give us a better performance experience.

9. Use mongoDB in express

1. Understand the attributes and models of mongoose.

2. Mongoose is an object model tool of mongoDB. It is a nodejs driver of mongoDB based on node-mongodb-native and can be executed in an asynchronous environment. At the same time, it is also an object model library for mongoDB operations, encapsulating some common methods such as adding, deleting, modifying and querying documents by mongoDB, which makes it easier for nodejs to operate mongoDB databases.

If you want to create a set through mongoose and add, delete, modify and query it, you need to use Schema (data attribute Model), Model, Entity.

3. Schema (attribute)

In Mongoose, everything starts with Schema, and every Schema is mapped to a collection in MongoDB. Schema defines the template (or framework) for documents in collection. A kind of database model skeleton stored in file form, which does not have the operation ability of the database, is only a representation of the database model in the program fragments, which can be said to be the data attribute model (table structure in the traditional sense). Or the model skeleton of a collection. The basic attribute types are string, date, numeric, Boolean, null, array, embedded document, and so on.

Var blogSchema = new Schema ({/ / Schema initials are capitalized, because Schema is the constructor title: String, comments: [{body: String, date: Date}], / / object array date: {type: Date, default: Date.now}, / / set the default value hidden: Boolean, meta: {/ / nested object votes: Number, favs: Number}} via default)

4. Model (model)

In order to use a defined Schema, we need to convert blogSchema into a model that we can use (actually compiling Schema to model, so all definitions of Schema have to be done before compile). In other words, model is the handle that we can operate on.

The model generated by Schema construction not only has the database skeleton defined by Schema, but also has the behavior of database operation, which is similar to the class that manages the attribute and behavior of data.

Var Blog = mongoose.model ('Blog', blogSchema); / / compile model

So we get a model named Blog. When model is generated, the corresponding collection in MongoDB is also established. The name of model is Blog, and the name of collection is the plural of model name, that is, blogs by default. (careful friends will find that not only the plural is changed, but also all the letters are lowercase, so the test is like this. [models generated by Schema releases, database operation pairs with abstract attributes and behaviors]

/ / create a model that you can use to manipulate the person collection in the database, referring to the whole. Create a person collection var PersonModel = db.model ("person", PersonSchema)

Person: the name of the collection in the database. If the person already exists, it will be saved to its directory when we add data to it. If it does not exist, the person collection will be created, and then the data will be saved. With model, you have the ability to manipulate data. To create a Model model, you need to specify two points: 1, the name of the collection, and 2, the Schema structure object of the collection. If you meet these two points, you can manipulate the database.

5. Understanding of Schema and model

Different from relational database, MongoDB is a document database, in which Scheme, model, collection and document are the four major elements. Document is the basic storage unit in MongoDB, and collection is the collection of many similar document. Schema defines a template for a class of document, so that this kind of document has a specific composition and storage mode in the database. While Schema only defines what Document looks like, the generation of document and various operations on document (additions, deletions, modifications and queries) are carried out through the corresponding model.

It is important to note that in MongoDB, only collection and document,Schema and model are actually tools in the process of defining and generating the first two.

6. Starter case

/ / 2 load module var mongoose = require ("mongoose"); / / 3. The name of the connection database mongod server-side mongo client / / database may not exist to create a zf database var db = mongoose.connect ("mongodb://123.57.143.189:27017/zf"); / / if the connection succeeds, the error callback db.connection.on will be executed ("error", function (error) {console.log ("database connection failed:" + error);}) / / if the connection is successful, open callback db.connection.on will be executed ("open", function () {console.log ("database connection successful");}) / / define a schema that describes what fields are in this collection and what types of fields are / / only attributes in 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, which can be used to manipulate the person collection in the database, referring to the overall var PersonModel = db.model ("person", PersonSchema); / / creating an entity based on the model refers to the individual object var personEntity = new PersonModel ({name: "zf", age: 6, email: "zf@qq.com", home:'beijing'}) / / use save method to save yourself to personEntity.save (function (error,doc) {if (error) {console.log ("error:" + error);} else {console.log (doc);}})

7. Basic operation of mongoose

① query:

Db.Userl.find ({conditions}, {options}, callback) conditions Object type / / query condition options Object type / / query configuration parameter callback Function / / callback db.teacher.find (). Pretty () / / plus pretty, the returned result is easier to read (show the effect on the command line)

There are many types of queries, such as conditional queries, filtering queries and so on. If options is omitted or null, all properties are returned; if the number of attributes to be displayed is set to greater than zero in options, this property is returned, _ id does not specify default return, setting _ id to 0 does not return this property, other fields are not specified, and default is not returned.

PersonModel.find ({}, function (error,docs) {/ / conditions displays all data under the model} if empty) / / query all data under the Article model db.Article.find ({}, function (err, docs) {if (err) {console.log ('error' + err); return;} res.json (docs); / / output in json format})

MPersonModel doesn't need new anymore, so you can use it immediately after getting it with var PersonModel = db.model ("person", PersonSchema);. The Schema object needs to be new.

A query returns a subset of documents in a collection. The mongoose model provides find, findOne, and findById methods for document queries.

FindOne query single bar, when a query meets the criteria of data, it will stop continuing the query and return the query results.

/ / create a model, which can be used to manipulate the person collection in the database, which refers to the overall var PersonModel = db.model ("person", PersonSchema) / / specifies that the returned field 1 means that 0 will not be returned, / / if the field is not specified, it will be returned by default / / _ id will be returned if it is not specified. If you do not want it to return, you need to explicitly specify 0PersonModel.find ({}, {name:1, age:1, _ id:0}, function (err,docs) {/ / find returns all the data in an array format. Each item in the array is a json console.log (docs) }) / / when the first matching record is found, it will be returned immediately, and the search will not continue. A single object / / findOne will return the first matched data in the format of a jsonPersonModel.findOne ({name:/ ^\ Wend9 $/}, {name:1, age:1, _ id:0}, function (err,doc) {console.log (doc)). }) / / query PersonModel.findById by ID ('56ee117356acb568054dd6d4, {name:1, age:1, _ id:0}, function (err,doc) {console.log (doc);})

② save | | add

Save is an instance method, which needs to be instantiated by new Model () first.

/ / create an entity based on the model, which refers to the individual object var personEntity = new PersonModel ({name: "zf", age: 6, email: "zf@qq.com", home:'beijing'}); / / save yourself to the database with save method personEntity.save (function (error,doc) {if (error) {console.log ("error:" + error);} else {console.log (doc)) }) / / Save a user information, fields in the document object model that userobj created for you Correctly correspond to the passed const userobj= {email: query, passworld: req.body.passworld, hash: hash, isregister: false, score: 5, sign: [], signdate:'} new db.MUser (userobj) .save (function (error) {if (error) {res.status (500). Send () return} res.json ({statu: 200}))

③ data update

Model.update (query conditions, update objects, callback) updates a document by default. If you want to update all of them, you need to add {multi:true}.

/ / create a model, which can be used to manipulate the person collection in the database, referring to the overall var PersonModel = db.model ("person", PersonSchema); / / the $set updater specifies the field to be updated var update = {$set: {age: 100}} / update / / multi updates all records matched to PersonModel.update ({name: 'zf'}, update, {multi:true}, function (error) {if (error) {console.log (error);} else {console.log (' Update matching records');}}) / / Update the content of the field content under the specified email field data entry. If it does not exist, create the field db.Share.update ({email: email}, {$set: {content: newarr}}, function (err, docs) {if (err) {res.status (500). Send (); return} res.json ({statu: 200}) }) / / $set specifies the value of the field, which is created if it does not exist. Can be any type supported by MondoDB. Article.update ({_ id: id}, {$set: {views: 51, title: 'modified title'... }}) / / $unset is the same as above, delete a field Article.update ({views: 50}, {$unset: {views: 'remove'}}) / / after execution: the views field does not exist / / $inc modifier, only valid for numbers. Article.update ({_ id: id}, {$inc: {views: 1}}) / / $push is an array of content push data Article.update ({_ id: id}, {$push: {message: messageobj}}) / / $pop deletes a single element from the header or tail (1 is deleted from the back,-1 is deleted from the front) db.Article.update (({_ id: id)) {$pop: {relationships:-1}) / / _ $pull__ deletes elements that meet the criteria Delete more than one db.Article.update (({_ id: id), {$pull: {"relationships": {"fname": "dongren", "lname": "zeng"})

④ data deletion

Model.remove (query criteria, callback)

PersonModel.remove ({name:'zf'}, function (err,docs) {/ / result: {ok: 1, n: 3} console.log (docs);}); db.Course.remove ({_ id: req.body.id}, function (err,docs) {if (err) {res.status (500). Send (); return} res.json ({statu: 200})})

⑤ Limit ()

The limit () method accepts a numeric parameter that specifies the number of records read from the MongoDB.

Only two records are displayed: db.student.find (). Limit (2). Pretty () / shows the first two records in the student collection

If the number value in limit () is empty, it means to find out all of them.

⑥ skip ()

The skip () method skips the specified amount of data, and the skip method also accepts a numeric parameter as the number of skipped records.

Skip the first three records: db.student.find (). Pretty (). Skip (3)

Show only the fourth record: db.student.find (). Pretty (). Limit (1) .skip (3) or db.student.find (). Pretty (). Skip (3) .limit (1)

⑦ sort sort ()

The sort () method can specify the sorted fields by arguments, and use 1 and-1 to specify how to sort, where 1 is ascending and-1 is used for descending.

Db.COLLECTION_NAME.find () .sort ({KEY:1})

Sorts the documents in the Student collection in ascending order of age: db.student.find (). Sort ({age:1})

[note] there is no requirement for the order of skip () and limit (). No matter how they are placed, the order in which they are executed is first sort (), then skip () and last limit ().

⑧ count

Calculate the total number of data in the database

⑨⑩⑪⑫

Use the visual graphics software robomongo:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report