恕我直言,牛逼哄哄的MongoDB你可能只会30% (3)

创建一个实体类,对应MongoDB的集合

@Data @Document(collection = "article_info") public class Article { @Id @GeneratedValue private Long id; @Field("title") private String title; @Field("url") private String url; @Field("author") private String author; @Field("tags") private List<String> tags; @Field("visit_count") private Long visitCount; @Field("add_time") private Date addTime; }

最终存储到数据中的格式如下:

{  "_id" : ObjectId("5e141148473cce6a9ef349c7"),     "title" : "批量更新",      "url" : "http://cxytiandi.com/blog/detail/8",      "author" : "yinjihuan",      "tags" : [         "java",          "mongodb",          "spring"     ],      "visit_count" : NumberLong(10),      "add_time" : ISODate("2019-02-11T07:10:32.936+0000") } 插入数据 Article article = new Article(); article.setTitle("MongoTemplate 的基本使用 "); article.setAuthor("yinjihuan"); article.setUrl("http://cxytiandi.com/blog/detail/1"); article.setTags(Arrays.asList("java", "mongodb", "spring")); article.setVisitCount(0L); article.setAddTime(new Date()); mongoTemplate.save(article);

数据库语法

db.article_info.save({ "title": "批量更新", "url": "http://cxytiandi.com/blog/detail/8", "author": "yinjihuan", "tags": [ "java", "mongodb", "spring" ], "visit_count": NumberLong(10), "add_time": ISODate("2019-02-11T07:10:32.936+0000") }) 更新数据 Query query = Query.query(Criteria.where("author").is("yinjihuan"));  Update update = Update.update("title", "MongoTemplate") .set("visitCount", 10);  mongoTemplate.updateMulti(query, update, Article.class);

数据库语法

db.article_info.updateMany( {"author":"yinjihuan"},  {"$set":   {     "title":"MongoTemplate",      "visit_count": NumberLong(10)   } } ) 删除数据 Query query = Query.query(Criteria.where("author").is("yinjihuan"));  mongoTemplate.remove(query, Article.class);

数据库语法

db.article_info.remove({"author":"yinjihuan"}) 查询数据 Query query = Query.query(Criteria.where("author").is("yinjihuan"));  List<Article> articles = mongoTemplate.find(query, Article.class);

数据库语法

db.article_info.find({"author":"yinjihuan"}) 存储文件 File file = new File("/Users/yinjihuan/Downloads/logo.png"); InputStream content = new FileInputStream(file); // 存储文件的额外信息,比如用户ID,后面要查询某个用户的所有文件时就可以直接查询 DBObject metadata = new BasicDBObject("userId", "1001"); ObjectId fileId = gridFsTemplate.store(content, file.getName(), "image/png", metadata); 源码参考

https://github.com/yinjihuan/spring-cloud/tree/master/Spring-Cloud-Book-Code-2/ch-17/mongodb

客户端推荐

下载地址:

https://studio3t.com/download/

图片

spring-boot-starter-mongodb-pool

最后推荐一个我自己写的小框架:Spring Boot中增强Mongodb的配置,多数据源,连接池

https://github.com/yinjihuan/spring-boot-starter-mongodb-pool

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wppfdg.html