当前位置:网站首页>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"));
}
边栏推荐
- Redis如何实现多可用区?
- webRTC SDP mslabel lable
- ASP. Net large takeout ordering system source code (PC version + mobile version + merchant version)
- 黑马程序员-软件测试-10阶段2-linux和数据库-44-57为什么学习数据库,数据库分类关系型数据库的说明Navicat操作数据的说明,Navicat操作数据库连接说明,Navicat的基本使用,
- World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection
- 最长公共子序列 - 动态规划
- 强联通分量
- Section - left closed right open
- 3W principle [easy to understand]
- STM32+BH1750光敏传感器获取光照强度
猜你喜欢
SaaS multi tenant solution for FMCG industry to build digital marketing competitiveness of the whole industry chain
Redis如何实现多可用区?
Thymeleaf th:with use of local variables
Security analysis of Web Architecture
Section - left closed right open
【leetcode周赛总结】LeetCode第 81 场双周赛(6.25)
CyCa children's physical etiquette Ningbo training results assessment came to a successful conclusion
【NVMe2.0b 14-9】NVMe SR-IOV
Thymeleaf th:classappend attribute append th:styleappend style append th:data- custom attribute
Interview shock 62: what are the precautions for group by?
随机推荐
Online electronic component purchasing Mall: break the problem of information asymmetry in the purchasing process, and enable enterprises to effectively coordinate management
Interview shock 62: what are the precautions for group by?
【NVMe2.0b 14-9】NVMe SR-IOV
CPU设计实战-第四章实践任务二用阻塞技术解决相关引发的冲突
启牛证券账户怎么开通,开户安全吗?
乌卡时代下,企业供应链管理体系的应对策略
Principle and performance analysis of lepton lossless compression
Shanghai under layoffs
微帧科技荣获全球云计算大会“云鼎奖”!
[summary of leetcode weekly competition] the 81st fortnight competition of leetcode (6.25)
分享 12 个最常用的正则表达式,能解决你大部分问题
useMemo,memo,useRef等相关hooks详解
[C question set] of Ⅷ
PostgreSQL 13 installation
PHP - fatal error: allowed memory size of 314572800 bytes exhausted
SaaS multi tenant solution for FMCG industry to build digital marketing competitiveness of the whole industry chain
Matrix chain multiplication dynamic programming example
Countermeasures of enterprise supply chain management system in UCA Era
SSL证书错误怎么办?浏览器常见SSL证书报错解决办法
Topology visual drawing engine