当前位置:网站首页>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 (***)
边栏推荐
猜你喜欢
CMake教程Step4(安装和测试)
WR | Jufeng group of West Lake University revealed the impact of microplastics pollution on the flora and denitrification function of constructed wetlands
First day of learning C language
Redis+caffeine two-level cache enables smooth access speed
哈趣K1和哈趣H1哪个性价比更高?谁更值得入手?
IDC报告:腾讯云数据库稳居关系型数据库市场TOP 2!
IDEA 项目启动报错 Shorten the command line via JAR manifest or via a classpath file and rerun.
c#图文混合,以二进制方式写入数据库
33:第三章:开发通行证服务:16:使用Redis缓存用户信息;(以减轻数据库的压力)
Judge whether a string is a full letter sentence
随机推荐
关于mysql中的json解析函数JSON_EXTRACT
The third lesson of EasyX learning
Detailed explanation of printf() and scanf() functions of C language
stirring! 2022 open atom global open source summit registration is hot!
Embedded-c Language-4
Domain name resolution, reverse domain name resolution nbtstat
MYSQL group by 有哪些注意事项
First day of learning C language
CVPR 2022 best student paper: single image estimation object pose estimation in 3D space
Complete solution instance of Oracle shrink table space
Tips for extracting JSON fields from MySQL
張平安:加快雲上數字創新,共建產業智慧生態
mysql中取出json字段的小技巧
CMake教程Step6(添加自定义命令和生成文件)
【7.7直播预告】《SaaS云原生应用典型架构》大咖讲师教你轻松构建云原生SaaS化应用,难题一一击破,更有华为周边好礼等你领!
2022年信息系统管理工程师考试大纲
IDEA 项目启动报错 Shorten the command line via JAR manifest or via a classpath file and rerun.
thinkphp模板的使用
菜刀,蚁剑,冰蝎,哥斯拉的流量特征
Database design in multi tenant mode