当前位置:网站首页>Mongdb learning notes
Mongdb learning notes
2022-07-05 14:38:00 【JavaSupeMan】
1.NoSQL Characteristics
It's a non relational database , Storage in document form
characteristic : The document database stores data in the form of documents ,BSON Format , similar JSON, It's a collection of data items . Each data item has a name and a corresponding value , Values can be simple data types , Such as a string / Numbers / Date, etc. . It can also be a complex type .
== advantage :== Data structure requirements are not strict , Variable table structure , You don't need to predefine the table structure like a relational database
== shortcoming :== Poor query performance , Lack of uniform query syntax
Application scenarios : journal ,web Application etc. 
Start command :
--dbpath: Specify the directory where the data file is stored
--logpath: Specify log files , Note that the specified file is not a directory
--logappend: Log by appending
--port: Designated port , The default is 27017
--bind_ip: Binding services IP, If bound 127.0.0.1, Can only be accessed locally , Default to local address
mongod --dbpath D:\MongDB\data\db




3. Safety certification
Create administrator account
# To set the administrator user name and password, you need to switch to admin library
use admin
# Create administrator
db.createUser({
user:"fox",pwd:"fox",roles:["root"]})
# View all user information
show users
# Delete user
db.dropUser("fox")
# Log in with the user , Default to admin library
mongo -ufox -pfox --authenticationDatabase=admin
4.MongoDB The document operation
1. Inserted into the document
2. Query the document
db.collection.find(query,projection)
db.collection.findOne(query,projection)
*query: Optional , Use the query operator to specify the query criteria
*projection: Optional , Use the projection operator to specify the returned key
Query cross reference table 

example :
example :
Check stock out users All data in
db.users.find()
Conditions of the query , Inquire about user The value is root Of
db.users.find({user:“root”})
Query a value greater than a certain number
db.users.find({age:{$gt:60}})
Find the first
db.users.findOne()
Sort & Pagination
stay MongoDB Use in sort() Method to sort the data
# Specify by collection (favCount) Return in descending order -1 Representation of descending order Expressing ascending order
favCount type All field names
db.books.find({
type:"travel"}).sort({
favCount:-1})
Paging query : adopt skip and limit To achieve ,skip Indicates the specified number of skipped records ,limit It means to limit the number of returned results
example :
db.books.find().skip().limit(5)
3. Update the document
It can be used update Command to update the specified data , The command format is as follows :
db.collection.update(query,update,options)
db.collection.updateOne(query,update,options) // Update individual documents amount to multi The attribute is true
db.collection.updateMany(query,update,options) // Update multiple documents
db.collection.replaceOne(query,update,options) // Replace a single document
# Attribute interpretation :
# query : Describe the updated query criteria
# update: Describe the updated actions and new content
# options: Describe the options for updating
# - upsert: Optional , If it doesn't exist update The record of , Whether to insert a new record . Default false, Do not insert
- multi: Optional , Whether to update all the multiple records queried by criteria . Default false, Update only the first record found
- writeConcern: Optional , Determine how many nodes a write operation falls on before it is considered successful ( Similar to transaction operation )
update The operators are as follows :
example :
db.books.update({
type:"novel"},{
$Set:{
publishedDate:new Date()}},{
"multi":true})
Be careful : If udate The update description in the command does not contain any operators , that MongoDB It will realize the of documents replace semantics
example :
db.books.update({
type:"novel"},{
age:"1"})
Will find type by novel The data of , Then its contents are completely replaced , Only age:1
findAndModify command :
Find and update , Only single documents can be operated , Cannot operate on multiple documents
Format :
example : increase new :true, The updated value will be returned ,false Return the value before update
db.books.findAndModify({
query:{
},update:{
}},new :true)
findOneAndUpdate: Update a single document and return to the pre update ( Or after update ) Documents
findOneAndReplace: Replace a single document and return to the previous ( Or after replacement ) Documents
4. Delete the document
remove command
example :
example :
db.books.remove({
age:28}) // Delete age be equal to 28 The record of
db.books.remove({
age:{
$lt:25}}) // Delete age Less than 25 The record of
db.books.remove({
}) // Delete all records
If there are more than one qualified , But only delete the first , You need to make justOne Parameters of , The format is as follows
example :
example :
db.books.remove({
age:28},true)
delete command :
Official recommendation deleteOne() and deleteMany() Method delete stable , The syntax is as follows :
example :
db.books.deleteMany({
}) // Delete all documents under the collection
db.books.deleteMany({
type:"novel"}) // Delete all data with specified conditions
db.books.deleteOne({
type:"novel"}) // Specify the data of the condition , Delete only the first
If you need to return the deleted document
command :findOneAndDelete
example :
db.books.findOneAndDelete({
type:"novel"}) // Delete all documents under the collection
MongoDB Integrate SpringBoot
1 Introduce dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.yml File configuration
spring:
data:
mongodb:
uri: mongodb://fox:[email protected]:27017/user?authSource=admin
#uri Equivalent to the following configuration
# database: user
# host: 127.0.0.1
# port: 27017
# username: fox
# password: fox
# authentication-database: admin
3. Inject bean
@Autowired
MongoTemplate mongoTemplate;
4. Use
1. Add, delete and change the set
// Operations on collections
@RequestMapping("/test1")
public void ok(){
// Determine whether a set exists
boolean flag = mongoTemplate.collectionExists("emp");
if(flag){
// Delete the collection
mongoTemplate.dropCollection("emp");
}
// Create set
MongoCollection<Document> emp1 = mongoTemplate.createCollection("emp");
}
// Querying documents
@RequestMapping("/test2")
public void test2(){
//============= Common query ====================
// Find all documents
List<User> list = mongoTemplate.findAll(User.class);
// according to ID Inquire about
User us = mongoTemplate.findById(1, User.class);
// The query result is multiple , Return to the first one
User u = mongoTemplate.findOne(new Query(), User.class);
//============= Conditions of the query =====================
// Build query criteria
Query query1 = new Query(Criteria.where("salary").gte(8000));
Query query2 = new Query(Criteria.where("salary").gte(8000).lt(10000));
Query query3 = new Query(Criteria.where("name").regex(" Zhang ")); // Fuzzy matching
//============== Multiconditional query ===================
Criteria criteria1 = new Criteria();
Criteria criteria2 = new Criteria();
//and Conditions
criteria1.andOperator(Criteria.where("age").gt(25),Criteria.where("salary").gt(8000));
//or Conditions
criteria1.orOperator(Criteria.where("age").gt(25),Criteria.where("salary").gt(8000));
Query query = new Query(criteria1);
//sort Sort
query.with(Sort.by(Sort.Order.desc("salary")));
// Pagination
query.skip(1).limit(10);
// Find all documents , The third parameter is the set name
List<User> list = mongoTemplate.findAll(query, TestUser.class, "test2");
}
// Document update operation
@RequestMapping("/test3")
public void test3(){
// First, find out what you want to modify
Query query = new Query(Criteria.where("salary").gte(8000));
User u = mongoTemplate.findOne(query, User.class);
Update update = new Update();
update.set("name"," Zhang San ");
//UpdateResult()
//UpdateFirst() Update the first record that meets the condition
//UpdateMulti() Update all records that meet the conditions
//upsert() If there are no qualified records, insert data
UpdateResult updateResult = mongoTemplate.upsert(query, update, User.class);
// Return the number of modified records
System.out.println(updateResult.getModifiedCount());
}
2. Inquire about
Use bson Query as query criteria
//1. Construct query conditions
Bson filters = Filters.and(
Filters.eq("deviceId", warningEvent.getDeviceId()),
Filters.gte("date", strTime.getTime()),
Filters.lte("date", endTime.getTime()),
Filters.eq("lastUpdateTime", DateUtil.format(updateDate, "yyyy-MM-dd HH:mm"))
);
//2. Specify field sort , Ascending or descending
Bson sort = Sorts.ascending("name");
// Bson sort = Sorts.descending("name");
//3. Specify the return field
List<String> list = new ArrayList<>();
list.add("name");
list.add("age");
// Inclusion Contains the specified fields and ( implicit )_id Field
// Exclusion Contains the specified fields and ( implicit )_id Field
Bson fields = Projections.fields(Projections.include(list));
//4. To query in the specified set
MongoCursor<Document> mongoCursor = mongoTemplate.getCollection("weatherall").find(filters).projection(fields).sort(sort).iterator();
while (mongoCursor.hasNext()) {
Document document = mongoCursor.next();
//3. Get data according to the field name
wdspList.add(document.getDouble("name"));
wdirList.add(document.getDouble("age"));
//document.getInteger()
lstDate.add(DateUtil.format(new Date(document.getLong("date")), "yyyy-MM-dd HH:mm"));
}
边栏推荐
- 直播预告|如何借助自动化工具落地DevOps(文末福利)
- How to choose the appropriate certificate brand when applying for code signing certificate?
- 用 Go 跑的更快:使用 Golang 为机器学习服务
- The speed monitoring chip based on Bernoulli principle can be used for natural gas pipeline leakage detection
- 分享 12 个最常用的正则表达式,能解决你大部分问题
- Share 20 strange JS expressions and see how many correct answers you can get
- 长列表优化虚拟滚动
- Isn't it right to put money into the external market? How can we ensure safety?
- 世界环境日 | 周大福用心服务推动减碳环保
- 【NVMe2.0b 14-9】NVMe SR-IOV
猜你喜欢

家用电器行业商业供应链协同平台解决方案:供应链系统管理精益化,助推企业智造升级

区间 - 左闭右开

IPv6与IPv4的区别 网信办等三部推进IPv6规模部署

Change multiple file names with one click

网上电子元器件采购商城:打破采购环节信息不对称难题,赋能企业高效协同管理

Opengauss database source code analysis series articles -- detailed explanation of dense equivalent query technology (Part 2)

Sharing the 12 most commonly used regular expressions can solve most of your problems

浅谈Dataset和Dataloader在加载数据时如何调用到__getitem__()函数

非技术部门,如何参与 DevOps?

Microframe technology won the "cloud tripod Award" at the global Cloud Computing Conference!
随机推荐
How to make a second clip of our media video without infringement
【華為機試真題詳解】歡樂的周末
Is the securities account given by the head teacher of qiniu school safe? Can I open an account?
Thymeleaf 常用函數
强联通分量
Intelligent supply chain collaboration system solution for daily chemical products industry: digital intelligent SCM supply chain, which is the "acceleration" of enterprise transformation
CPU设计实战-第四章实践任务二用阻塞技术解决相关引发的冲突
Thymeleaf th:with use of local variables
How to choose the appropriate certificate brand when applying for code signing certificate?
Thymeleaf 模板的创建与使用
Loop invariant
TS所有dom元素的类型声明
Detailed explanation of usememo, memo, useref and other relevant hooks
ASP.NET大型外卖订餐系统源码 (PC版+手机版+商户版)
How can non-technical departments participate in Devops?
Thymeleaf 使用后台自定义工具类处理文本
最长公共子序列 - 动态规划
How to open an account of qiniu securities? Is it safe to open an account?
CPU设计实战-第四章实践任务三用前递技术解决相关引发的冲突
【招聘岗位】软件工程师(全栈)- 公共安全方向