当前位置:网站首页>Mongodb learning
Mongodb learning
2022-06-30 04:23:00 【No bug program yuan】
1. install MongoDB: My next version 3.2
MongoDB Community Download | MongoDB
https://www.mongodb.com/try/download/community2. Configure environment variables :
C:\Program Files\MongoDB\Server\5.0\bin Add to environment variables Inside path in
3. start-up mongoDB, open cmd( Path is not related ) Input mongod

visit localhost:27017 On behalf of success
Custom database data Path and port number command :mongod --dbpath Database path --port Port number ( No more than 65535)
Database client :
-- The client is used to operate the server , Add, delete, modify and query data
-- mongo: Start client
take MongoDB Set as system service , Can start automatically in the background , No need to start manually every time
1. stay C Disk creation data Of db and log Catalog .
2. Installation directory bin There is a mongod.cfg file , Good configuration data and log The catalog of
3. Open command line window as Administrator
4. Execute the following command :
4.1 stay C Disk creation data/db
4.2 perform sc.exe create MongoDB binPath="\"C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe" --service --config=\"C:\Program Files\MongoDB\Server\3.2\mongod.cfg"" DisplayName= "MongoDB" start= "auto"
Then close all cmd Can also access , It means success .
Basic instructions :
show dbs,show databases Display all current databases
db Indicates the current database
show collections Show all collections in the database
Database CRUD( Additions and deletions ) operation
Insert a document into the database :
db.stus.insert<<name:"sunwukong",age:18,gender:"male">>;
Successfully returns WriteResult<<"nlnserted":1>>
db.stus.find() Query the data in the document
db.stus.find({_id:"hello"}) lookup id by hello Documents
findOne() Return an object ,find It returns an array
db.stus.find({num:{$gt:500}}) lookup num Greater than 500 Of
db.stus.find({num:{$eq:500}}) lookup num be equal to 500 Of
db.stus.find({num:{$lt:500}}) lookup num Less than 500 Of
db.stus.find({num:{$gt:40,$lt:50}}) lookup num Greater than 40 Less than 50 Of
db.stus.find().limit(10); Before display 10 Data
db.stus.find().skip(10).limit(10); skip= Page number -1,limit( Number of entries per page ),mongoDB Can adjust skip and limit The order of , So the order doesn't matter skip(10).limit(10) According to the first 11 To 20 Numbers
db.stus.find({}).sort({sal:1,empno:-1}); sort() It can be used to specify the collation of documents
1 Expressing ascending order -1 Representation of descending order
db.stus.find({},{ename:1,_id:0,sal:1}); The position of the second parameter sets the displayed field
Modify to the database :
By default, the old object is replaced with the new object , hold name by 33 The whole object of , There's only one property age by 2:db.stus.update({name:"33",age:2});
Modifying is not replacing the entire object , The first {} It's a matching condition :
db.stus.update({"_id":ObjectId("59c219689410bcc0709")},
{$set:{gender:" male ",address:" Liusha River "}})
unset Used to delete specified attributes :
db.stus.updateMany Modify multiple ,update Only one is changed by default
db.stus.updateOne To modify a
Delete... To the database :
db.stus.remove(), Must pass reference , Delete all eligible documents , Multiple... Are deleted by default , The second parameter is true, Only one... Is deleted , If you don't pass the parameters , Will empty the collection ( Slightly poor performance , Because it will match before deleting , If you want to empty, just empty the collection db.stus.drop()).
db.stus.deleteOne() Delete one that meets the conditions
db.stus.deleteMany() Delete multiple matching
mongoose The benefits of :
You can create a schema structure for a document (Schema)
Objects in the model can be / Document validation
Data can be converted to an object model through type conversion
Middleware can be used to apply business logic hooks
Than Node Native MongoDB Easier to drive
1. Download and install Mongoose
stay mongodb Graphical tools (mongodbmanagerpro) Carry out orders :
npm i mongoose --save
2. Introduce in the project mongoose
var mongoose=require("mongoose")
3. Connect mongodb database
Example :
var mongoose=require{"mongoose"};
mongoose.connect("mongodb://127.0.0.1/mongoose_test",{udrMonhoVlirny:true});
mongoose.connection.once("open",function(){
console.log(" Database connection successful ~~~")
})
mongoose.connection.once("close",function(){
console.log(" Database disconnected ~~~")
})
// disconnect
mongoose.disconnect();establish Schema:
var mongoose=require{"mongoose"};
mongoose.connect("mongodb://127.0.0.1/mongoose_test",{udrMonhoVlirny:true});
mongoose.connection.once("open",function(){
console.log(" Database connection successful ~~~")
})
var Schema=mongoose.Schema;
var stuSchema=new Schema({
name:String,
age:Number,
gender:{
type:String,
default:"female"
},
address:String
})
// adopt Schema To create Model
//Model Represents a collection in a database , adopt Model To operate on the database
//mongoose.model(modelName,schema)
//modelName, Is the name of the set to be mapped
var stuModel=mongoose.model("student",stuSchema)
stuModel.create({
name:" The Monkey King ",
age:18,
gender:"male",
address:" Huaguoshan "
},function(err){
if(!err){
console.log(" Insert the success ~~~~");
}
})
stuModel.find({name:" Tang's monk 123"},function(err,docs){
if(!err){
// It's an array , If only one field .docs[0].name
console.log(docs)
}
})
// It means as long as name and age Field shows , Don't _id This field
stuModel.find({},"name age -_id",function(err,docs){
if(!err){
console.log(docs)
}
})
// It means as long as name and age Field shows , Don't _id This field
stuModel.find({},"name age -_id",{skip:3,limit:1},function(err,docs){
if(!err){
console.log(docs)
}
})
// Return an object , Is not an array
stuModel.findOne({},function(err,doc){
if(!err){
console.log(docs)
}
})
//59c4c3cf4e5483191467 yes id Value
stuModel.findById("59c4c3cf4e5483191467",function(err,doc){
if(!err){
console.log(docs)
}
})update:
stuModel.findOne({},function(err,doc){
if(!err){
doc.update({$set:{age:28}},function(err){
if(!err){
console.log(" Modification successful !")
}
})
// Another way
doc.age=18
doc.save();
// Delete
doc.remove(function(err){
if(!err){
console.log(" Delete successful ~~~")
}
})
}
})
边栏推荐
- [learn FPGA programming from scratch -52]: high level chapter - FPGA development based on IP core - basic framework for IP core use (taking PLL as an example)
- Es2018 key summary
- 01 backpack, dynamic planning
- OneNote production schedule
- JS file block to Base64 text
- Matlab reads fig file and restores signal
- SQLyog导入数据库时报错,求帮解决!
- QT creator 8 beta2 release
- Thinkphp5 implements import function
- Explain the underlying principles of JVM garbage collection in simple terms
猜你喜欢

AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里

尝试链接数据库时出现链接超时报错,如何解决?

Five methods to clear floating and their advantages and disadvantages

Junior students summarize JS advanced interview questions

Junior students summarize JS basic interview questions

Node red series (28): communication with Siemens PLC based on OPC UA node

FortiGate configures multiple server IPS as link monitor monitoring objects on the same interface

Day 12 advanced programming techniques

Thingsboard tutorial (II and III): calculating the temperature difference between two devices in a regular chain

DBT product initial experience
随机推荐
基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
Es2017 key summary
Five methods to clear floating and their advantages and disadvantages
FortiGate firewall modifies the default timeout of a session
QT 6.3.1conan software package release
thinkphp5实现导入功能
Errno and PERROR
Quick sort & merge sort
JS reflect
SQL追加字段
Detailed explanation of network layer
How to use div boxes to simulate line triangles
The school training needs to make a registration page. It needs to open the database and save the contents entered on the registration page into the database
Find the interface and add parameters to the form
Machine learning notes
Unity 在編輯器中輸入字符串時,轉義字符的輸入
AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
[从零开始学习FPGA编程-52]:高阶篇 - 基于IP核的FPGA开发 - IP核使用的基本框架(以锁相环PLL为例)
基于ROS的SLAM建图、自动导航、避障(冰达机器人)
base64.c