当前位置:网站首页>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 | MongoDBhttps://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 ~~~")
}
})
}
})
边栏推荐
- Find the interface and add parameters to the form
- mysql更新数组形式的json串
- 基于servlet+jsp+mysql实现的工资管理系统【源码+数据库】
- 2021-07-14
- [Thesis reading | deep reading] dane:deep attributed network embedding
- 工程安全和工程质量
- Quick sort & merge sort
- Educoder group purchase suspension box page production
- El upload upload file (manual upload, automatic upload, upload progress)
- Default value of JS parameter
猜你喜欢
什么是光耦电路,实际使用中应该注意些什么?
Sql语句遇到的错误,求解
FortiGate configures multiple server IPS as link monitor monitoring objects on the same interface
Configure specific source IP in SLA detection of FortiGate sdwan
el-upload上传文件(手动上传,自动上传,上传进度)
El upload upload file (manual upload, automatic upload, upload progress)
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
Huawei cloud native - data development and datafactory
[cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)
Myrpc version 2
随机推荐
Slam mapping, automatic navigation and obstacle avoidance based on ROS (bingda robot)
RPC correction based on arcpy API
什么是光耦电路,实际使用中应该注意些什么?
How to write a conditional statement to obtain the value of the maximum time in a table using a MySQL statement
在大厂外包呆了三年,颠覆了我的认知!
lego_ Reading and summary of loam code
FortiGate firewall modifies the default timeout of a session
OneNote production schedule
Error in conditional filter (if) syntax in sum function in SQL Server2005
Grasp grpc communication framework in simple terms
Salary management system based on servlet+jsp+mysql [source code + database]
AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
Stack implementation integrated Calculator - code implementation
Ora-00907: missing right parenthesis problem supplement
DBT product initial experience
Detailed explanation of network layer
FortiGate firewall filters the specified session and cleans it up
Indefinite parameters of JS function
第九天 脚本與資源管理
7-3 single source shortest circuit for strange play upgrade