mongodb学习随笔一
db数据:
book:
book_msg:
user:
部分有记录的数据代码:
db.book.insertMany([{ id: 1, name: "西游记", tag: ["四大名著", "神魔类"] }, { id: 2, name: "红楼梦", tag: ["四大名著", "家族类"] }, { id: 3, name: "三国演义", tag: ["四大名著", "战场类"] }, { id: 4, name: "水浒传", tag: ["四大名著", "战场类"] }, { id: 5, name: "聊斋", tag: ["神魔类"], mark: "很吓人" }])
管道,聚合:
db.user.aggregate([{$match:{name:{$regex:"五"}}},{$group:{_id:"$_id",age:{$sum:"$age"}}}]) db.user.aggregate([{$match:{name:{$regex:"五"}}},{$count:"id"}]) db.user.aggregate([{$match:{name:{$regex:"五"}}}]) db.book.aggregate([{$match:{id:{$gt:1}}},{$unwind:"$tag"}]) db.book.aggregate([{$match:{id:{$gt:1}}},{$unwind:"$mark"}]) db.book.aggregate([{$match:{id:{$gt:1}}},{$unwind:{path:"$tag",includeArrayIndex:"arrayIndex"}}]) db.book.aggregate([{$match:{id:{$gt:1}}},{$unwind:{path:"$tag",preserveNullAndEmptyArrays:true}}]) db.book.aggregate([{$match:{id:{$gt:1}}},{$unwind:{path:"$tag",preserveNullAndEmptyArrays:false}}]) db.book.aggregate([{$match:{id:{$gt:1}}},{$unwind:"$tag"},{$group:{_id:["$name","$tag"]}}]) db.book.aggregate([{$match:{id:{$gt:1}}},{$unwind:"$tag"},{$group:{_id:["$name","$tag"]}}]) db.book.aggregate() db.book.aggregate([{$limit:3}]) db.book.aggregate([{$skip:2}]) db.book.aggregate([{$skip:2},{$sort:{id:-1}}]) db.book.aggregate([{$sort:{id:-1}},{$skip:2}]) db.book.aggregate([{$skip:1},{$sort:{id:-1,_id:1}}]) db.book.insertMany([{id:6,name:"龍族",tag:["魔法类"],mark:"好看",msg_id:1},{id:7,name:"凡人修仙传",tag:["神魔类"],mark:"很精彩",msg_id:2}]) db.book_msg.insertMany([ {id:1,msg:["第一部,火之晨曦","第二部,悼亡者之瞳","第三部,黑暗之潮","第四部,奥丁之渊","第五部,悼亡者归来"]}, {id:2,msg:["人界篇","灵界篇","仙界篇"]} ]) db.book.aggregate([ {$lookup:{ from: "book_msg", localField: "msg_id", foreignField: "id", as: "book_msg" } } ]).pretty() db.book.aggregate([{$match:{mark:{$ne:null}}}]) //可在mongosh运行 db.book.mapReduce( function(){emit(this.name, this.tag)}, function(key, values){return Array.sum(values)}, { query: {mark:{$ne:null}}, out: "new_book" } ) db.new_book.find()
maven(springboot版本2.7.4):
<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.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
yml:
server: port: 8083 spring: data: mongodb: uri: mongodb://username:password@ip:post/mydb?authSource=mydb
配置bean注入:
@Configuration public class MongoConfig { @Value("${spring.data.mongodb.uri}") private String connectionString; @Bean public MongoTemplate mongoTemplate() { MongoDatabaseFactory dbFactory = new SimpleMongoClientDatabaseFactory(connectionString); DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(dbFactory); MongoMappingContext mappingContext = new MongoMappingContext(); mappingContext.setAutoIndexCreation(true); mappingContext.afterPropertiesSet(); return new MongoTemplate(dbFactory, new MappingMongoConverter(dbRefResolver, mappingContext)); } }
model:
@Data @NoArgsConstructor @AllArgsConstructor @Document public class User { @Id private Long id; @Field private String name; @Field private Integer age; @Field private Date birthday; }
测试方法:
@Test void test(){ /*boolean b = mongoTemplate.collectionExists(User.class); if(b){ mongoTemplate.dropCollection(User.class); } MongoCollection<Document> collection = mongoTemplate.createCollection(User.class);*/ User user = new User(2L, "李四", 18, new Date()); List<User> users = Arrays.asList(new User[]{ new User(3L, "王五", 19, new Date()), new User(4L, "赵六", 20, new Date()), new User(5L, "田七", 15, new Date()), new User(6L, "王老五", 39, new Date()), new User(7L, "张老四", 41, new Date()), }); mongoTemplate.insert(users, User.class); }
@Test void query(){ System.out.println("========================================================="); List<User> all = mongoTemplate.findAll(User.class); System.out.println(all); System.out.println("========================================================="); Query query = new Query(Criteria.where("name").regex("张")); List<User> users = mongoTemplate.find(query, User.class); System.out.println(users); System.out.println("========================================================="); Criteria criteria = new Criteria(); criteria.andOperator(Criteria.where("name").regex("张"), Criteria.where("age").gt(12).lt(30)); List<User> users1 = mongoTemplate.find(new Query(criteria), User.class); System.out.println(users1); }
@Test void page(){ System.out.println("========================================================="); List<User> users = mongoTemplate.find(new Query().skip(2).limit(3).with(Sort.by(Sort.Order.desc("id"))), User.class); System.out.println(users); }
@Test void jsonQ(){ System.out.println("========================================================="); Query query = new BasicQuery("{name:'张三'}"); List<User> users = mongoTemplate.find(query, User.class); users.forEach(System.out::println); System.out.println("========================================================="); String json = "{$and:[{age:{$gt:12}},{name:{$regex:'张'}}]}"; query = new BasicQuery(json); List<User> users1 = mongoTemplate.find(query, User.class); users1.forEach(System.out::println); }
@Test void update(){ /*Query query = new Query(new Criteria().and("_id").is(1)); Update update = new Update(); update.set("name", "张三丰满"); UpdateResult upsert = mongoTemplate.upsert(query, update, User.class); System.out.println(upsert);*/ //mongoTemplate.updateFirst(new Query(Criteria.where("name").regex("张")), new Update().set("name", "张三"), User.class); mongoTemplate.updateMulti(new Query(Criteria.where("name").regex("张")), new Update().set("age", 28), User.class); }
@Test void remove(){ mongoTemplate.remove(new Query(new Criteria().and("_id").is(7)), User.class); }
@Test void aggregate(){ TypedAggregation typedAggregation = new TypedAggregation(User.class, Aggregation.match(Criteria.where("name").regex("五")), Aggregation.group("id").sum("age").as("age")); //TypedAggregation typedAggregation = new TypedAggregation(User.class, Aggregation.match(Criteria.where("name").regex("五"))); AggregationResults<User> aggregate = mongoTemplate.aggregate(typedAggregation, User.class); aggregate.getMappedResults().forEach(System.out::println); }
@Test void createIndexes(){ Index index = new Index(); index.on("name", Sort.Direction.ASC).on("age", Sort.Direction.DESC); mongoTemplate.indexOps(User.class).ensureIndex(index); }
@Test void getIndexes(){ List<IndexInfo> indexInfo = mongoTemplate.indexOps(User.class).getIndexInfo(); indexInfo.forEach(System.out::println); //输出结果 //IndexInfo [indexFields=[IndexField [ key: _id, direction: ASC, type: DEFAULT, weight: NaN]],
//name=_id_, unique=false, sparse=false, language=, partialFilterExpression=null, collation=null, expireAfterSeconds=null] //IndexInfo [indexFields=[IndexField [ key: name, direction: ASC, type: DEFAULT, weight: NaN],
//IndexField [ key: age, direction: DESC, type: DEFAULT, weight: NaN]], name=name_1_age_-1, unique=false, sparse=false, language=,
//partialFilterExpression=null, collation=null, expireAfterSeconds=null] }