北京中燕建設公司網(wǎng)站自己在家怎么做電商
MongoDB介紹
SpringBoot簡單使用MongoDB
一、配置步驟
1、application.yml
2、pom
3、entity
4、mapper
二、案例代碼使用
1、庫
前期準備上一篇安裝MongoDB地址http://t.csdn.cn/G4oYJ
跟關系型數(shù)據(jù)庫概念對比
Mysql MongoDB
Database(數(shù)據(jù)庫) Database(數(shù)據(jù)庫)
Table(表) Collection(集合)
Row(行) Document(文檔)
Column(列) Field(字段)
數(shù)據(jù)格式
MongoDB 將數(shù)據(jù)存儲為一個文檔,BSON格式。由key 和 value組成。
{"_id" : ObjectId("61d6927658c3b5acf4723616"),"name" : "希望小學","studentNum" : 10000.0
}
使用場景
大數(shù)據(jù)量存儲場景
MongoDB自帶副本集和分片,天生就適用于大數(shù)量場景,無需開發(fā)人員通過中間件去分庫分表,非常方便。
操作日志存儲
很多時候,我們需要存儲一些操作日志,可能只需要存儲比如最近一個月的,一般的做法是定期去清理,在MongoDB中有固定集合的概念,我們在創(chuàng)建集合的時候可以指定大小,當數(shù)據(jù)量超過大小的時候會自動移除掉老數(shù)據(jù)。
爬蟲數(shù)據(jù)存儲
爬下來的數(shù)據(jù)有網(wǎng)頁,也有Json格式的數(shù)據(jù),一般都會按照表的格式去存儲,如果我們用了MongoDB就可以將抓下來的Json數(shù)據(jù)直接存入集合中,無格式限制。
社交數(shù)據(jù)存儲
在社交場景中使用 MongoDB 存儲存儲用戶地址位置信息,通過地理位置索引實現(xiàn)附近的人,附近的地點等。
電商商品存儲
不同的商品有不同的屬性,常見的做法是抽出公共的屬性表,然后和SPU進行關聯(lián),如果用MongoDB的話那么SPU中直接就可以內(nèi)嵌屬性。
CRUD
單個文檔插入到集合中
db.collection.insertOne()
多個文檔插入到集合中
db.collection.insertMany()
單個或者多個文件插入到集合中
db.collection.insert()
查詢數(shù)據(jù)
db.collection.find( )
更新單條
db.inventory.updateOne()
更新多條
db.inventory.updateMany()
刪除單條文檔
db.inventory.deleteOne( )
刪除多條文檔
db.inventory.deleteMany()
開發(fā)工作必用
MongoDB跟Mysql的語法對比
https://blog.csdn.net/qq_42483764/article/details/122350164
MongoDB基礎操作
db.集合名稱.insert/save/insertOne(文檔) //添加
db.集合名稱.update({條件},{操作種類:{文檔}})
db.集合名稱.remove(條件)
示例:
db.book.save({'name':'spring boot',type:'spring boot'}) //添加
db.book.remove({type:'spring boot'}) //刪除//修改第一條
db.book.update({name:'spring boot'}, {$set:{name:'Spring Boot'}})
//修改所有
db.book.updateMany({name:'spring boot'}, {$set:{type:'spring'}})
db.getCollection('book').find({}) //查詢
db.book.find({type:'spring boot'}) //查詢
定義核心配置文件
# 登錄用戶所在的數(shù)據(jù)庫
spring.data.mongodb.authentication-database=admin# 數(shù)據(jù)庫的ip地址
spring.data.mongodb.host=192.168.133.142# MongoDB端口號
spring.data.mongodb.port=27017# 用戶賬號
spring.data.mongodb.username=zlfeng# 用戶密碼
spring.data.mongodb.password=123456# 指定使用的數(shù)據(jù)庫
# 不必預先創(chuàng)建,不存在該數(shù)據(jù)庫會自動創(chuàng)建
spring.data.mongodb.database=db_student
修改yml配置
spring:data:mongodb:#192.168.217.128根據(jù)自己的ip進行修改#test是MongoDB的集合名稱 也就是表名
添加實體類
@Data
@AllArgsConstructor
@Document("User") //指定了這個模型類型所對應的集合名稱即collection 表名
public class User {@Id //自動生成的主鍵ID 主鍵 不可重復 自帶索引private String id;private String name;private Integer age;
}
方法測試
@SpringBootTest
public class MongoTemplateTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void testMongoDB(){//向表中插入數(shù)據(jù)User user = new User(null,"張三",20);User user1 = new User(null,"李四",16);mongoTemplate.insert(user);mongoTemplate.insert(user1);//查詢表中所有記錄List<User> userList = mongoTemplate.findAll(User.class);System.out.println(userList);//[User(id=63acf541e6af652ac74fd008, name=張三, age=20),// User(id=63acf541e6af652ac74fd009, name=李四, age=16)]//根據(jù)表中id查詢記錄User user2 = mongoTemplate.findById("63acf541e6af652ac74fd008", User.class);System.out.println(user2);//User(id=63acf541e6af652ac74fd008, name=張三, age=20)//條件查詢Query query = new Query(Criteria.where("name").is("李四").and("age").is(16));List<User> users = mongoTemplate.find(query, User.class);System.out.println(users);//[User(id=63acf541e6af652ac74fd009, name=李四, age=16)]//根據(jù)_id刪除表中記錄Query query2 = new Query(Criteria.where("_id").is("63acf541e6af652ac74fd008"));DeleteResult remove = mongoTemplate.remove(query2, User.class);//獲取刪除記錄的個數(shù)long count = remove.getDeletedCount();System.out.println(count);//1//刪除表中所有數(shù)據(jù)Query query3 = new Query();mongoTemplate.remove(query3,User.class);}
}
二、基于MongoRepository開發(fā)
Spring Data提供了對MongoDB數(shù)據(jù)訪問的支持,我們只需要繼承MongoRepository類,按照Spring Data規(guī)范就可以了。
構建倉庫
public interface UserRepository extends MongoRepository<User,String> {
}
方法測試
@SpringBootTest
public class MongoRepositoryTest {@Autowiredprivate UserRepository userRepository;@Testpublic void test(){//向數(shù)據(jù)庫表中插入數(shù)據(jù)User user = new User(null,"張三三",18);User user1 = new User(null,"李四",16);userRepository.save(user);userRepository.save(user1);//查詢數(shù)據(jù)庫表中所有記錄List<User> all = userRepository.findAll();System.out.println(all);//[User(id=63acf24938e0d1033d50dc20, name=張三三, age=18),// User(id=63acf24938e0d1033d50dc21, name=李四, age=16)]//按照id查詢表中數(shù)據(jù)User user2 = userRepository.findById("63acf24938e0d1033d50dc20").get();System.out.println(user2);//User(id=63acf24938e0d1033d50dc20, name=張三三, age=18)//按條件(姓名與年齡)查詢Example<User> example = Example.of(new User(null,"李四",16));List<User> list = userRepository.findAll(example);System.out.println(list);//User(id=63acf24938e0d1033d50dc21, name=李四, age=16)//模糊查詢User user3 = new User(null,"三",18);//模糊查詢匹配規(guī)則ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);//忽略大小寫Example<User> example1 = Example.of(user3,matcher);List<User> list1 = userRepository.findAll(example1);System.out.println(list1);//User(id=63acf24938e0d1033d50dc20, name=張三三, age=18)//分頁查詢Pageable pageable = PageRequest.of(0, 2);//設置分頁參數(shù):第1頁 每頁2條數(shù)據(jù)Page<User> page = userRepository.findAll(pageable);System.out.println("Page的總頁數(shù)是:" + page.getTotalPages() + ",Page的總記錄條數(shù)是:" + page.getTotalElements());//Page的總頁數(shù)是:1 + ,Page的總記錄條數(shù)是:2//根據(jù)_id修改信息User user4 = userRepository.findById("63acf24938e0d1033d50dc20").get();user4.setName("王五");//將取出的信息修改其nameuserRepository.save(user4);//根據(jù)id刪除userRepository.deleteById("63acf24938e0d1033d50dc20");//刪除全部userRepository.deleteAll();}
一、配置步驟
進入mongodb中創(chuàng)建數(shù)據(jù)庫和用戶
# (1)授權
# 我的管理員是root,密碼是123456
db.auth("root", "123456")# (2)創(chuàng)建應用數(shù)據(jù)庫和用戶
# 連接庫直接使用相應庫中的用戶名稱即可,如果僅僅使用appdb庫,直接使用user=appdb,pwd=123456連接即可
use appdb
db.createUser({user:'appdbuser', pwd:'123456', roles:[ {role:'dbOwner', db:'appdb'} ]})
1、application.yml
#數(shù)據(jù)庫配置
spring:data:mongodb:# mongodb://用戶名:密碼@IP地址:27017/數(shù)據(jù)庫uri: mongodb://appdbuser:123456@127.0.0.1:27017/appdb# 可以不用設置數(shù)據(jù)庫# database: appdb
2、pom
org.springframework.boot spring-boot-starter-data-mongodb3、entity
@Document("book")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {@Idprivate Long id;private String title;private Integer page;
}
4、mapper
@Repository
public interface BookDao extends MongoRepository<Book, Integer> {
}
二、案例代碼使用
@SpringBootTest
@Slf4j
class MymongoApplicationTests {@Autowiredprivate BookDao bookDao;@Testvoid contextLoads() {// 插入多條數(shù)據(jù)Book book1 = new Book(2L, "China", 8);Book book2 = new Book(3L, "American", 8);ArrayList<Book> bookArrayList = Lists.newArrayList();bookArrayList.add(book1);bookArrayList.add(book2);bookDao.saveAll(bookArrayList);// 查詢一條數(shù)據(jù)Book book3 = new Book();book3.setTitle("American");Example<Book> example = Example.of(book3);Optional<Book> one = bookDao.findOne(example);log.info(one.get().toString());//Book(id=3, title=American, page=8)}
}
操作集合下的文檔
- 切換至集合
連接至具體數(shù)據(jù)庫以后,使用以下代碼切換到集合,如果集合不存在,則使用如下代碼新建集合:
MongoCollection collection = database.getCollection("myTestCollection");
- 插入文檔
切換至集合后,就可以進行文檔的增、刪、改、查操作。首先定義文檔,并使用 append。方法追加內(nèi)容,代碼如下:
Document document = new Document("_id", 1999).append("title", "MongoDB Insert Demo").append("description","database").append("likes", 30).append("by", "demo point").append("url", "http://c.biancheng.net/mongodb/");
document 為 BSON 類型的文檔,實際上為一個列表,每項有兩個元素,即字段名和值。
文檔定義完成后,再使用 insertOne 方法將此文檔插入集合:
collection.insertOne(document);
如果插入多條數(shù)據(jù),需要先定義一個 Document 列表,然后用 add() 方法添加多個 Document 元素,最后用 insertMany() 方法插入,代碼如下:
List<Document> documents = new ArrayList<Document>();documents.add(document1);collection.insertMany(documents);
- 刪除文檔
使用 delete() 方法刪除一個或多個文檔,代碼如下:
collection.deleteOne(document);collection.deleteMany(new Document ("likes", 30));
- 更新數(shù)據(jù)
使用 updataOne() 方法更新一條數(shù)據(jù)或多個數(shù)據(jù),代碼如下:
collection.updataOne (eq ("likes", 30), new Document ("$set", new Document ("likes", 50)));
updateOne() 方法中有兩個參數(shù),第一個參數(shù)表示更新的內(nèi)容等于 (“l(fā)ikes”,30) 的文檔,第二個參數(shù)為要修改的內(nèi)容,使用 $set 參數(shù)修改當前值,修改的內(nèi)容為 (“l(fā)ikes”, 50)。
- 查詢數(shù)據(jù)
利用游標類型實現(xiàn)數(shù)據(jù)的查詢和遍歷顯示,使用游標前需要 import MongoCursor 類庫。
import com.mongodb.client.MongoCursor;document Doc = (Document)collection.find(eq("likes", 30)).iterator();MongoCursor<Document> cursor =collection.find().iterator();try{while (cursor.hasNext()){System.out.printin(cursor.next().toJson());}} finally{Cursor.close();
}
設置 find() 方法的參數(shù)為查詢條件,參數(shù)為比較的 Document 元素。
- 其他方法
刪除數(shù)據(jù)庫或集合,代碼如下:
mDatabase.drop();collection.drop();
關閉客戶端連接,代碼如下:
mongoClient.close();