2019 MongoDB 入門教程
歡迎轉載,轉載請註明網址:https://blog.csdn.net/qq_41910280
簡介:一篇入門級別MongoDB教程。
1. MongoDB安裝
Windows:
進入bin目錄下
mongod --dbpath D:\develop\MongoDB\data\db --logpath " D:\develop\MongoDB\data\logs\mongo.log " --logappend
管理員cmd添加服務:
mongod --dbpath “D:\develop\MongoDB\data\db” --logpath “D:\develop\MongoDB\data\logs\mongo.log” --logappend --install --serviceName “MongoDB”
之後執行命令(管理員): net start MongoDB
刪除服務
mongod --remove --serviceName “MongoDB”
Linux:
進入bin目錄下 可選: export PATH=$PATH:/usr/local/mongodb/bin
查看版本 ./mongo -version
創建mongo.cfg文件
dbpath=/usr/local/mongodb/data/db
logpath=/usr/local/mongodb/data/logs/mongodb.log
#後臺運行
fork=true
bind_ip=0.0.0.0
logappend=true
首先, 將bind_ip改爲0.0.0.0 (讓其他電腦可以訪問,用於遠程連接,如果bind_ip是127.0.0.1的話,就只能本地訪問)
配置文件啓動 mongod -f /usr/local/mongodb/bin/mongo.cfg
停止 ./mongod -shutdown -dbpath=/usr/local/mongodb/data/db
連接 ./mongo
cmd啓動 ./mongod -dbpath=/usr/local/mongodb/data/db -logpath=/usr/local/mongodb/data/logs/mongodb.log -logappend -port=27017 -fork # 不修改bind_ip 遠程無法訪問
常用的啓動參數:
–dbpath:指定存儲數據的文件夾
–logpath:指定日誌存儲文件
–logappend:日誌以增加方式產生
–port指定端口,如果不寫的話,默認是27017
–fork代表後臺運行
2. mongo命令CRUD
使用 mongo IP:port 連接mongo server(不指定IP端口默認連接127.0.0.1:27017)
2.1 基本命令
show dbs 展示mongodb中的數據庫
use dbname 切換或創建數據庫
show collections 展示當前數據庫中的集合
2.2 增加文檔
db.collection.save(bson) 保存bson對象到collection // 如果collection不存在會自動創建
2.3 查詢文檔
db.collection.find() 查詢全部數據
其中_id相當於主鍵, 如果我們沒有指定該字段, mongodb會自動生成
提示: 使用db.help()或db.collection.help()或db.collection.find().help()命令打開幫助
查詢電話是12222222222的數據, 注意字段類型
還有findOne()只查詢一條記錄
limit()限制結果數量
2.4 修改文檔
原來的孫悟空只剩下_id 和age兩個字段了
如何保留其他字段呢?
通過$set
這些命令不用記, 我都是猜的, 猜不出來的命令不是好命令
2.5 刪除文檔
附:
測試數據
db.user.save({name:"沙和尚",sex:"男",age:25,address:"流沙河路11號"});
db.user.save({name:"唐僧",sex:"男",age:35,address:"東土大唐"});
db.user.save({name:"白骨精",sex:"女",age:18,address:"白骨洞"});
db.user.save({name:"白龍馬",sex:"男",age:20,address:"西海"});
db.user.save({name:"哪吒",sex:"男",age:15,address:"蓮花灣小區"});
2.6 高級查詢
模糊查詢
MongoDB的模糊查詢是通過正則表達式的方式實現的。格式爲:
/模糊查詢字符串/
如果要查詢name字段中以“白”開頭的,代碼如下:
大於小於不等於
db.collection.find({ “field” : { $gt: value } } ); // 大於: field > value
db.collection.find({ “field” : { $lt: value } } ); // 小於: field < value
db.collection.find({ “field” : { $gte: value } } ); // 大於等於: field >= value
db.collection.find({ “field” : { $lte: value } } ); // 小於等於: field <= value
db.collection.find({ “field” : { $ne: value } } ); // 不等於: field ≠ value
判斷字段是否存在
$exists
示例:查詢所有含有address字符的文檔
示例:查詢所有不含有address字符的文檔
包含與不包含
包含使用$in操作符。
示例:查詢student集合中age字段包含20,25,30的文檔
示例:查詢student集合中age字段不包含20,25,30的文檔
統計記錄條數
count()
條件連接
並且: $and 或者: $or
示例:查詢student集合中age大於等於20 並且age小於30的文檔
查詢student集合中sex爲女,或者年齡小於20的文檔記錄
3. Java連接MongoDB
見https://github.com/Spark4J/mongodb-demo
4. spring-data-mongodb
springboot 2.1.3 ( spring-data-mongodb 2.1.5 )
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
實體類
package com.example.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@NoArgsConstructor
@AllArgsConstructor
//@Document("customer")// 不指定collection默認是customer
public class Customer {
@Id
public String id;
public String firstName;
public String lastName;
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
DAO
package com.example.dao;
import com.example.domain.Customer;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface CustomerRepository extends MongoRepository<Customer, String> {
public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
}
Test
package com.example;
import com.example.dao.CustomerRepository;
import com.example.domain.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private CustomerRepository repository;
@Test
public void contextLoads() {
repository.deleteAll();
// save a couple of customers
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
// fetch all customers
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
// fetch an individual customer
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : repository.findByLastName("Smith")) {
System.out.println(customer);
}
}
}
結果
Customers found with findAll():
-------------------------------
Customer(id=5ca428dfcbd6cd0614c11211, firstName=Alice, lastName=Smith)
Customer(id=5ca428dfcbd6cd0614c11212, firstName=Bob, lastName=Smith)
Customer found with findByFirstName('Alice'):
--------------------------------
Customer(id=5ca428dfcbd6cd0614c11211, firstName=Alice, lastName=Smith)
Customers found with findByLastName('Smith'):
--------------------------------
Customer(id=5ca428dfcbd6cd0614c11211, firstName=Alice, lastName=Smith)
Customer(id=5ca428dfcbd6cd0614c11212, firstName=Bob, lastName=Smith)
是不是意猶未盡 ~ ↓↓↓
點擊成爲磚(guang)家(tou)... (逃
參考文獻
- spring guide
神奇的小尾巴:
本人郵箱:[email protected] [email protected]
[email protected] 歡迎交流,共同進步。
歡迎轉載,轉載請註明本網址。