美文网首页
mongodb语法使用

mongodb语法使用

作者: knock | 来源:发表于2024-02-17 23:40 被阅读0次
    package com.alipay;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.alipay.config.mongodb.MongoEntity;
    import lombok.extern.slf4j.Slf4j;
    import org.bson.Document;
    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.data.domain.Sort;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.aggregation.Aggregation;
    import org.springframework.data.mongodb.core.aggregation.AggregationResults;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.core.query.Update;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.List;
    
    /***
     * @ClassName: com.alipay.MongoTest
     * @Description: TODO
     * @author: yanyd
     * @Date: 14:05 2020/4/18
     * @version : V1.0
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @Slf4j
    public class MongoTest {
    
        @Autowired
        private MongoTemplate mongoTemplate;
    
        @Test
        public void insert() {
            //db.getCollection("def_student").save( {"name":"wo","age":"19"})
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            MongoEntity mongoEntity = new MongoEntity();
            mongoEntity.setAge("20");
            mongoEntity.setName("test1");
            mongoEntity.setSex("M");
            mongoEntity.setNum(1.2);
            mongoEntity.setBirth(simpleDateFormat.format(new Date()));
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("par", "hy");
            jsonObject.put("xsf", "re");
            jsonArray.add(jsonObject);
            mongoEntity.setArr(jsonArray);
            MongoEntity insert = mongoTemplate.insert(mongoEntity);
            log.info(insert.get_id().toString());
            log.info(JSONObject.toJSONString(insert));
        }
    
        @Test
        public void query_and() {
            /**
             * db.getCollection("def_student").find(
             *         {
             *           "name":{
             *             "$regex":"test",
             *             "$options":""
             *           },
             *           "birth":{
             *             "$gte":"2020-04-19 14:34:50",
             *             "$lte":"2020-04-22 13:34:50"
             *           },
             *           "age":{
             *             "$in":[
             *               "18",
             *               "19",
             *               "20"
             *             ]
             *           },
             *           "num":1.2,
             *           "arr":{
             *             "$elemMatch":{
             *               "or":[
             *                 {
             *                   "name":"test"
             *                 },
             *                 {
             *                   "name":"test1"
             *                 }
             *               ]
             *             }
             *           }
             *         }
             * )
             */
            Query query = new Query();
            query.addCriteria(new Criteria("name").regex("test"));
            query.addCriteria(new Criteria("birth").gte("2020-04-19 14:34:50").lte("2020-04-22 13:34:50"));
            query.addCriteria(new Criteria("age").in(new String[]{"18", "19", "20"}));
            query.addCriteria(new Criteria("num").is(1.2));
            query.addCriteria(new Criteria("arr").elemMatch(new Criteria().andOperator(new Criteria("name").is("test"), new Criteria("name").is("test1"))));
            log.info(query.toString());
            List<MongoEntity> mongoEntityList = mongoTemplate.find(query, MongoEntity.class);
            log.info(JSON.toJSONString(mongoEntityList));
        }
    
        @Test
        public void query_or() {
            //or
            Query query = new Query();
            query.addCriteria(new Criteria().orOperator(new Criteria("name").is("test"), new Criteria("name").is("test1")));
            query.addCriteria(new Criteria("age").is("18"));
            log.info(query.toString());
            List<MongoEntity> mongoEntityList = mongoTemplate.find(query, MongoEntity.class);
            log.info(JSON.toJSONString(mongoEntityList));
        }
    
        @Test
        public void query_sort_skip_limit() {
            //query_sort_skip_limit
            Query query = new Query();
            query.addCriteria(new Criteria("name").regex("t"));
            query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"),new Sort.Order(Sort.Direction.DESC,"num")));
            query.skip(3);
            query.limit(3);
            log.info(query.toString());
            List<MongoEntity> mongoEntityList = mongoTemplate.find(query, MongoEntity.class);
            for (int i = 0; i < mongoEntityList.size(); i++) {
             log.info(mongoEntityList.get(i).get_id().toString());
            }
            log.info(JSON.toJSONString(mongoEntityList));
        }
    
        @Test
        public void update() {
            //update
            Update update = new Update();
            update.set("param", "param1");
            log.info(update.toString());
            mongoTemplate.updateFirst(new Query().addCriteria(new Criteria("name").is("test2")), update, MongoEntity.class);
        }
    
        @Test
        public void push_addSet() {
            //push_addSet  addToSet是数组类型 拆分插入[{},{}]  直接插入[[]]
            Update update = new Update();
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("k1", "v3");
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("k2", "v");
            jsonArray.add(jsonObject);
            jsonArray.add(jsonObject1);
            //拆分插入
            update.addToSet("param2").each(jsonArray);
           //直接插入数组
            update.addToSet("param3", jsonArray);
            log.info(update.toString());
            mongoTemplate.updateFirst(new Query().addCriteria(new Criteria("name").is("test2")), update, MongoEntity.class);
        }
    
        @Test
        public void pull() {
            //pull 移除数组中的对象
            Update update = new Update();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("k1", "v1");
            update.pull("param1", jsonObject);
            log.info(update.toString());
            mongoTemplate.updateFirst(new Query().addCriteria(new Criteria("name").is("test")), update, MongoEntity.class);
        }
    
        @Test
        public void aggregate() {
            //aggregate
            Aggregation customerAgg = Aggregation.newAggregation(
                    Aggregation.match(new Criteria("name").regex("test")),
                    Aggregation.group("name","sex")
                            .sum("num").as("num")
                            .count().as("count")
                            .addToSet("num").as("num_addToSet")
                            .push("num").as("num_push")
                            .first("num").as("num_first")
                            .last("num").as("num_last")
                            .min("num").as("num_min")
                            .max("num").as("num_max"),
                     Aggregation.sort(new Sort(new Sort.Order(Sort.Direction.DESC, "num"))),
                    Aggregation.skip(0L),
                    Aggregation.limit(100L)
            );
            log.info(customerAgg.toString());
            AggregationResults<Document> aggregationResults = mongoTemplate.aggregate(customerAgg, MongoEntity.class, Document.class);
            Iterator<Document> iterator = aggregationResults.iterator();
            while (iterator.hasNext()) {
                Document document = iterator.next();
                log.info(document.toJson());
            }
        }
    
    
        @Test
        public  void  moreandor(){
            //多个$and  $or的情况
            //{ "$and" : [{ "$and" : [{ "age" : "test" }, { "age" : "test1" }] }, { "$and" : [{ "age" : "test" }, { "age" : "test1" }] }] }
            Query query = new Query();
            Criteria[] list=new Criteria[2];
            Criteria criteria = new Criteria().orOperator(new Criteria("age").is("test"), new Criteria("age").is("test1"));
            list[0]=criteria;
            list[1]=criteria;
            query.addCriteria(new Criteria().andOperator(list));
            System.out.println(query.toString());
            List<MongoEntity> mongoEntityList = mongoTemplate.find(query, MongoEntity.class);
            log.info(JSON.toJSONString(mongoEntityList));
        }
    
    }
    

    相关文章

      网友评论

          本文标题:mongodb语法使用

          本文链接:https://www.haomeiwen.com/subject/sympadtx.html