当前位置:网站首页>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 ~~~")
}
})
}
})
边栏推荐
- Configure specific source IP in SLA detection of FortiGate sdwan
- iMile 利用 Zadig 多云环境周部署千次,跨云跨地域持续交付全球业务
- How to solve the problem of link hyperlinks when trying to link the database?
- Grasp grpc communication framework in simple terms
- JS file block to Base64 text
- Anonymous pipeline for interprocess communication
- Day 11 script and game AI
- mysql更新数组形式的json串
- 【WEBRTC】ADM: rtc_ include_ internal_ audio_ Device triggers RTC_ Dcheck (ADM) assertion
- win10系统使用浏览器下载后,内容无故移动或删除
猜你喜欢

Es2017 key summary

El upload Upload file (Manual upload, Automatic upload, upload progress)

SQLyog导入数据库时报错,求帮解决!

Myrpc version 0

Basic knowledge of redis

Technology sharing | broadcast function design in integrated dispatching

Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool

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

Jour 9 Gestion des scripts et des ressources

OneNote software
随机推荐
Matlab reads fig file and restores signal
lego_ Reading and summary of loam code
Anonymous pipeline for interprocess communication
base64.c
idea灰屏问题
Myrpc version 2
工程安全和工程质量
Modifier of JS regular expression
An error occurs when sqlyog imports the database. Please help solve it!
Stack implementation integrated Calculator - code implementation
SQLyog导入数据库时报错,求帮解决!
QT 6.3.1conan software package release
errno和perror
什么是光耦电路,实际使用中应该注意些什么?
lego_loam 代码阅读与总结
Day 12 advanced programming techniques
JS proxy
FortiGate creates multiple corresponding DDNS dynamic domain names for multiple ADSL interfaces
Jour 9 Gestion des scripts et des ressources
Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool