当前位置:网站首页>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 ~~~")
}
})
}
})
边栏推荐
- Es2017 key summary
- MySQL DDL change
- AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
- Robot slam navigation core technology and practice Season 1: Chapter 0_ Slam development overview
- Thingsboard tutorial (II and III): calculating the temperature difference between two devices in a regular chain
- 什么是光耦电路,实际使用中应该注意些什么?
- Iterator of JS
- You know AI, database and computer system
- [cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)
- [image fusion] multi focus and multi spectral image fusion based on cross bilateral filter and weighted average with matlab code
猜你喜欢

Myrpc version 0
![[fuzzy neural network prediction] water quality prediction based on fuzzy neural network, including Matlab source code](/img/88/038826ec6d16c8eb04d9ef2e01d47a.png)
[fuzzy neural network prediction] water quality prediction based on fuzzy neural network, including Matlab source code
![[image fusion] multi focus and multi spectral image fusion based on cross bilateral filter and weighted average with matlab code](/img/9c/2553d192c2f9b93acc6550220c447f.png)
[image fusion] multi focus and multi spectral image fusion based on cross bilateral filter and weighted average with matlab code

FortiGate firewall configuration log uploading regularly

OneNote software

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

Error encountered in SQL statement, solve

I get n offers in two months. I don't have any difficult interviewers here

两个月拿到N个offer,什么难搞的面试官在我这里都不算事

Myrpc version 2
随机推荐
[image fusion] multi focus and multi spectral image fusion based on cross bilateral filter and weighted average with matlab code
Find the interface and add parameters to the form
FortiGate firewall modifies the default timeout of a session
Project safety and quality
Memorize unfamiliar words at SSM stage and update them from time to time
找到接口在表单里加参数
Titanic(POJ2361)
FortiGate firewall configuration log uploading regularly
Clients accessing the daytime service (TCP)
【WEBRTC】ADM: rtc_ include_ internal_ audio_ Device triggers RTC_ Dcheck (ADM) assertion
A solution to the problem of "couldn't open file /mnt/repodata/repomd.xml"
Troubleshooting of abnormal communication between FortiGate and fortiguard cloud
Thinkphp5 implements import function
[从零开始学习FPGA编程-52]:高阶篇 - 基于IP核的FPGA开发 - IP核使用的基本框架(以锁相环PLL为例)
JS deconstruction assignment
Idea grey screen problem
Introduction to cloud native + container concept
Tea mall system based on SSM framework [project source code + database script + report]
FortiGate creates multiple corresponding DDNS dynamic domain names for multiple ADSL interfaces
Qt6 QML Book/Qt Quick 3D/Qt Quick 3D