当前位置:网站首页>Mongodb (quick start) (I)
Mongodb (quick start) (I)
2022-07-05 17:31:00 【Attacking polar bear】
Data address :
link :https://pan.baidu.com/s/1DxgX3RCvWfaKzziHG8IHZQ
Extraction code :3452
gitee Address
https://gitee.com/liushanshan126/mongodb-test
One 、mongdb Relevant concepts
1、mysql and mongdb contrast


2、bson(mongdb Storage structure , And json similar )
- Bson in , Except for the basic JSON type :string,integer,boolean,double,null,array and object
- mongo Special data types are also used . These types include date,object id,binary data,regular expression
and code. Each driver implements these types in a language specific way , Check the documentation of your driver for details .
Two 、 Single deployment
1、 Install compressed files , And create data/db file
2、 Single machine start command
Get into bin In the folder ,cmd Console , Enter the command :
mongod–dbpath=…\data\db
3、 ... and 、 Basic common commands
1、 establish 、 Display database

Be careful : Create database , But this database has no collection ( surface ) When , It will only exist in memory , Only when there is a collection in the current database can it be instantiated to the disk
2、 Delete
Enter the database that needs to be deleted , And then execute
db.dropDatabase()
3 、 insert data
db.comment.insert({“articleid”:“100000”,“content”:“ It's a beautiful day , The sun is shining ”,“userid”:“1001”,“nickname”:“Rose”,“createdatetime”:newDate(),“likenum”:NumberInt(10),“state”:null})
3、 Inquire about db.document.find({},{}):document Is a table ; The first brace : Query criteria , amount to where Later conditions ; The second brace : Show which fields , amount to select The following query fields
for example : db.article.findOne({articleid:‘12222’}, {userid:1, nickname:1}) Query field articleid by 12222 The data of , And only take out userid,nickname, _id( Default ) Field
4、 to update
4.1 、 General update ( Partial update $set)
db.article.update({_id:“2”},{$set:{likenum:NumberInt(889)}})
4.2 Column value increases ( Numbers + n) $inc
db.article.update({_id:“3”},{$inc:{likenum:NumberInt(1)}})
5、 Delete the document

6、 Sort sort
sort() Method can be used to specify the sorting field by parameter , And use 1 and -1 To specify how to sort , among 1 Arrange... In ascending order , and -1 It's for descending order .
db.COLLECTION_NAME.find().sort({KEY:1})
skip、limit、sort Execution order of
Follow mysql equally , Execute first sort, In execution skip, Finally, execute limit
7、 Regular expression

8、 Comparison query ( Greater than , Less than , Greater than or equal to , Less than or equal to , It's not equal to )

9、 contain (in), It doesn't contain (nin)
in:db.comment.find({userid:{ KaTeX parse error: Expected 'EOF', got '}' at position 19: …["1003","1004"]}̲}) nin:db.comme…nin:[“1003”,“1004”]}})
10、 Conditional connection .or and and Use

summary
Select switch database :usearticledb
insert data :db.comment.insert({bson data })
Query all the data :db.comment.find();
Condition query data :db.comment.find({ Conditions })
Query the first record that meets the criteria :db.comment.findOne({ Conditions })
Query the first few records that meet the criteria :db.comment.find({ Conditions }).limit( Number of pieces )
Query qualified skipped records :db.comment.find({ Conditions }).skip( Number of pieces )
Modifying data :db.comment.update({ Conditions },{ Revised data }) or db.comment.update({ Conditions },{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …t.update({ Conditions },{ inc:{ Self increasing field : Step value }})
Delete data :db.comment.remove({ Conditions })
Statistics query :db.comment.count({ Conditions })
Fuzzy query :db.comment.find({ Field name :/ Regular expressions /})
Conditional comparison operations :db.comment.find({ Field name :{$gt: value }})Contains the query :db.comment.find({ Field name :{ KaTeX parse error: Expected 'EOF', got '}' at position 11: in:[ value 1, value 2]}̲}) or db.comment.f…nin:[ value 1, value 2]}})
Conditional join query :db.comment.find({ KaTeX parse error: Expected 'EOF', got '}' at position 18: …d:[{ Conditions 1},{ Conditions 2}]}̲) or db.comment.fi…or:[{ Conditions 1},{ Conditions 2}]})
Four 、 Indexes
1、 type
Single field index 、 Composite index 、 Other indexes
2、 View index 、 establish 、 Delete
see :db.collection.getIndexes()
establish :
Single field index :db.comment.createIndex({userid:1})
Composite index :db.comment.createIndex({userid:1,nickname:-1})
Delete :
Single delete :db.comment.dropIndex({userid:1})
Delete all indexes :db.collection.dropIndexes()
3、 Use index as a condition , The query field is also an index , Then do not check the set , Direct query index

5、 ... and 、java Actual operation mongodb
1、 Introduce dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/>
<!--lookupparentfromrepository-->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Connect mongodb Dependence -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
2、dao

3、 Entity class

4、service
package com.bear.service;
import com.bear.dao.CommentRepository;
import com.bear.pojo.Comment;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Optional;
/** * < sketch > * < Detailed description > * * @author LiuShanshan * @version $Id$ */
@Service
public class CommentService {
@Resource
private CommentRepository commentRepository;
/** *< sketch > increase *< Detailed description > * @author Liushanshan * @param comment * @return void */
public void saveComment(Comment comment){
Comment save = commentRepository.save(comment);
System.out.println(save);
}
// Delete
public void delete(String id){
commentRepository.deleteById(id);
}
// Change
public void update (Comment comment){
commentRepository.save(comment);
}
// check
public Comment select (String id){
Optional<Comment> byId = commentRepository.findById(id);
Comment comment = byId.get();
return comment;
}
}
5、 Test class
@RunWith(SpringRunner.class)
@SpringBootTest(classes=MongodbApplication.class)
public class Test {
@Autowired
private CommentService commentService;
// preservation
@org.junit.Test
public void saveTest(){
Comment comment = new Comment();
comment.setArticleid("100000");
comment.setContent(" Test the added data ");
comment.setCreatedatetime(LocalDateTime.now());
comment.setUserid("1003");
comment.setNickname(" Caesar the great ");
comment.setState("1");
comment.setLikenum(0);
comment.setReplynum(0);
commentService.saveComment(comment);
}
// Inquire about
@org.junit.Test
public void select(){
Comment select = commentService.select("62bd78cc4e03471050ba849e");
System.out.println(select);
}
// to update
@org.junit.Test
public void update(){
Comment select = commentService.select("62bd78cc4e03471050ba849e");
select.setUserid("234234234");
commentService.update(select);
}
// Delete
}
6、 Paging condition query

6.1 Paging condition query 2.0

6.2 MongoTemplate Use (***)

边栏推荐
猜你喜欢
![[Web attack and Defense] WAF detection technology map](/img/7c/60a25764950668ae454b2bc08fe57e.png)
[Web attack and Defense] WAF detection technology map

thinkphp3.2.3

Check the WiFi password connected to your computer
Redis+caffeine two-level cache enables smooth access speed

统计php程序运行时间及设置PHP最长运行时间

解决“双击pdf文件,弹出”请安装evernote程序

MySQL之知识点(七)

北京内推 | 微软亚洲研究院机器学习组招聘NLP/语音合成等方向全职研究员

7. Scala class

33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)
随机推荐
Cartoon: interesting [pirate] question
哈趣K1和哈趣H1哪个性价比更高?谁更值得入手?
华为云云原生容器综合竞争力,中国第一!
The third lesson of EasyX learning
Check the WiFi password connected to your computer
漫画:有趣的海盗问题 (完整版)
Embedded UC (UNIX System Advanced Programming) -1
Judge whether a number is a prime number (prime number)
Redis+caffeine two-level cache enables smooth access speed
一口气读懂 IT发展史
MySQL之知识点(六)
漫画:寻找股票买入卖出的最佳时机
云安全日报220705:红帽PHP解释器发现执行任意代码漏洞,需要尽快升级
Detailed explanation of printf() and scanf() functions of C language
Machine learning 01: Introduction
33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)
WR | 西湖大学鞠峰组揭示微塑料污染对人工湿地菌群与脱氮功能的影响
ICML 2022 | Meta propose une méthode robuste d'optimisation bayésienne Multi - objectifs pour faire face efficacement au bruit d'entrée
Cmake tutorial step6 (add custom commands and generate files)
CMake教程Step3(添加库的使用要求)