• MongoDB复杂Json数据的增删改查


    本文讲解了MongoDB在java语言下的复杂用法,并附带案例。欢迎各位MongoDB使用者点赞收藏❥提出宝贵的意见。

    TImetableDO数据结构:

    {
      "orgId": "test_0c8bd2befcae",
      "level": 33,
      "studyStageCode": "test_4e6d1cb07db3",
      "startDate": 50,
      "endDate": 35,
      "timeTableName": "test_f3e7ab9cf540",
      "gradeTimetables": [
        {
          "gradeCode": "test_91d5ee05b73d",
          "gradeName": "test_616641b7e6db",
          "amStartTime": 30,
          "amStartMinute": 54,
          "amEndHour": 5,
          "amEndMinute": 80,
          "pmStartHour": 48,
          "pmStartMinute": 15,
          "pmEndHour": 68,
          "pmEndMinute": 13,
          "duration": 9,
          "classInterval": 77,
          "weeks": [
            {
              "weekNum": 92,
              "weekName": "test_a0c7db38d66e"
            }
          ],
          "lessons": [
            {
              "lessonCode": "test_2f27176bb524",
              "lessonName": "test_4877e17a365d"
            }
          ],
          "scheduleLessons": [
            {
              "weekNum": 27,
              "lessonCode": "test_64bb0f8f6297",
              "subjectCode": "test_5e4d93df1aa1",
              "subjectName": "test_ec76334cae9a",
              "teacherUser": "test_b8e5d0a1747a",
              "teacherName": "test_5977e370d39d",
              "mobile": "test_18747d63bc10",
              "schoolId": "test_c2ba7953dc06",
              "schoolName": "test_10e05269ab81"
            }
          ]
        }
      ],
      "createUser": "test_52c517640053",
      "createName": "test_de010b8aa98e",
      "updateUser": "test_dc57588627ac",
      "updateName": "test_8bf96510716a",
      "updateVersion": 21,
      "id": "test_d225da32cfd0",
      "createTime": "2014-10-29 02:07:11",
      "updateTime": "2029-08-08 02:34:23"
    }

     查询单条:

    示例1:二层结构查询

    1. //根据年级、课表id-查询发布后的课表结构学科数据
    2. Criteria criteria = Criteria.where(
    3. "timetableId").is(vo.getTimetableId())
    4. .and("gradeTimetables.gradeCode").is(vo.getGradeCode());
    5. TimetableD0 tablePublishDb = mongoTemplate.findOne(Query. query(criteria),TimetableD0.class);

    示例2:三层结构查询

    1. ScheduleLesson reqLesson = vo. getScheduleLessons.get(O) ;
    2. Criteria criteria = new Criteria();
    3. criteria.and("_id").is(new objectId(vo. getTimetableId())
    4. .and("gradeTimetables.gradeCode").is(vo.getGradeCode())
    5. .and("gradeTimetables.scheduleLessons.weekNum").is(reqLesson. getWeekNum())
    6. .and("gradeTimetables.scheculeLessons.lessonCode").is(reqLesson. getLessonCode());
    7. TimetableDO timetableD0 =mongoTemplate.findOne(Query.query(criteria),TimetableD0.class);

    多层结构类似上面的例子 

    新增数据:

    当新增的数据结构不存在时,会自动创建结构,可以使用这一方法,addToSet()

    1. criteria = new Criteria();
    2. criteria.and("_id").is(new 0bjectId(vo. getTimetableId())
    3. .and("gradeTimetables.gradeCode").is(vo.getGradeCode());
    4. Update update = new Update();
    5. Query upQuery =Query.query(criteria);
    6. upQuery = Query.query(criteria);
    7. update.addToSet("gradeTimetables.$.scheduleLessons",reqLesson) ;
    8. mongoTemplate.updateMulti(upQuery,update, mongoTemplate.getCollectionName(TimetableD0.class));

    当新增的数据scheduleLessons结构存在,需要将数据追加到 scheduleLessons集合下:

    TImetablePublishDO数据结构参考:

    {
      "timetableId": "test_9dcfb1cce278",
      "orgId": "test_6c11a4a0f541",
      "level": 6,
      "weekStartDate": 74,
      "weekOfYear": 22,
      "timeTableName": "test_83e2eb0eaabe",
      "gradeTimetables": [
        {
          "gradeCode": "test_595a3c80a607",
          "gradeName": "test_f81e785c7e37",
          "lessons": [
            {
              "lessonCode": "test_cee22164732a",
              "lessonName": "test_2729825d7999"
            }
          ],
          "weeks": [
            {
              "weekNum": 6,
              "weekName": "test_4737db2d42a7"
            }
          ],
          "scheduleLessons": [
            {
              "weekNum": 26,
              "lessonCode": "test_5b5b5aca5680",
              "subjectCode": "test_1c81759285bc",
              "subjectName": "test_8a8ece8aaf9b",
              "teacherUser": "test_312420e06c84",
              "teacherName": "test_fb466fa3d249",
              "schoolId": "test_0f6cc223fda5",
              "schoolName": "test_dc6722d6fea3",
              "mobile": "test_1e72b8116113"
            }
          ],
          "timetableResources": [
            {
              "weekStartDate": 70,
              "weekOfYear": 35,
              "weekNum": 78,
              "lessonCode": "test_b4cd7a853c20",
              "date": 84,
              "fileInfos": [
                {
                  "fileName": "test_11784cd6d2f6",
                  "fileCode": "test_ba01c998e683",
                  "fileId": "test_41d4c044c81b",
                  "duration": 65,
                  "status": 28,
                  "onlineStatus": 85,
                  "subjectCode": "test_8cba9df8ccd0"
                }
              ]
            }
          ]
        }
      ],
      "publishUser": "test_9e20649e2238",
      "publishName": "test_2f5c024039bf",
      "id": "test_ebcb7203fe31",
      "createTime": "2030-05-17 23:01:08",
      "updateTime": "2020-11-29 21:10:25"
    }

    TimeResourceDO数据结构参考:

    {
      "timetableId": "test_5e2f93818261",
      "weekStartDate": 89,
      "weekOfYear": 80,
      "weekNum": 1,
      "lessonCode": "test_8e463424b9b1",
      "date": 20,
      "fileInfos": [
        {
          "fileName": "test_e2b697819be4",
          "fileCode": "test_b6c34f601983",
          "fileId": "test_469de84fc88a",
          "duration": 95,
          "status": 18,
          "onlineStatus": 7,
          "subjectCode": "test_d48941813229"
        }
      ],
      "subjectCode": "test_263e36c523c6",
      "subjectName": "test_1e38e268f251",
      "teacherUser": "test_5938a6ff97b0",
      "teacherName": "test_65579a61503f",
      "mobile": "test_a9aac5d63aab",
      "schoolId": "test_8f7d77a2542f",
      "schoolName": "test_6f51eb0e4cdc",
      "gradeCode": "test_0bf604459300",
      "id": "test_0346e4939916",
      "createTime": "2015-06-13 00:32:46",
      "updateTime": "2020-02-28 23:55:50"

    1. //查询集合中是否存在,不存在则新增,存在则更新
    2. Criteria criteria = Criteria.where("timetableId").is(vo.getTimetableld())
    3. .and(" weekOfYear").is(DateUtil. getWeekOfYearAtMonday(LocalDate.now())).and("gradeCode") .is(vo.getGradeCode())
    4. .and("lessonCode").is(vo.getLessonCode()).and("weekNum").is(vo.getWeekMum())
    5. .and("date").is(vo.getDate()) ;
    6. if(mongoTemplate.count(Query.query(criteria),TimetableResourceD0.class)> 0){
    7. List fileList = vo.getFiles();
    8. List list = new ArrayList<~>() ;
    9. fileList.forEach(file ->{
    10. FileInfo fileInfo = new FileInfo();
    11. fileInfo.setFileCode(file.getFileCode());
    12. list.add(fileInfo) ;
    13. }) ;
    14. //更新内容
    15. Update update = new Update();
    16. Update.AddToSetBuilder f = update.addToSet("fileInfos");
    17. f.each(list);
    18. Query upQuery = Query.query(criteria) ;
    19. mongoTemplate.updatelulti(upQuery,update, mongoTemplate.getCollectionName(TimetableResourceD0.class));
    20. }
    21. else {
    22. TimetableResourceD0 resourceD0 = new TimetableResourceDOO;
    23. resourceD0 = packData(resourceD0, vo);
    24. mongoTemplate.insert(resourceD0);
    25. }

    更新数据:

    替换目标位置数据:(替换scheduleLessons集合),使用set、addToSet

    1. ScheduleLesson reqLesson = vo.getScheduleLessons().get(O);
    2. Criteria criteria = new Criteria();
    3. criteria.and("_id").is(new objectId(vo.getTimetableId()))
    4. .and("gradeTimetables.gradeCode").is(vo.getGradeCode())
    5. .and("gradeTimetables.scheduleLessons.weekNum ").is(reqLesson.getWeekNum())
    6. .and("gradeTimetables.scheduleLessons.lessonCode").is(reqLesson.getLessonCode());
    7. Query upQuery = Query. query(criteria);
    8. Update update = new Update().set("updateVersion", oldVersion + 1);
    9. TimetableDO timetableDO =mongoTemplate.findOne(upQuery,TimetableD0.class);
    10. if (objectUtil.isNotEmpty(timetableDO)){
    11. List scheduleLessons=timetableDO.getGradeTimetables().stream().
    12. filter(grade->
    13. ObjectUtil.equal(grade.getGradeCode(),vo.getGradeCode())
    14. .findFirst(
    15. .get().getScheduleLessons();
    16. scheduleLessons.removeIf(scheduleLesson->
    17. ObjectUtil.equal(scheduleLesson.getWeekNum(), reqLesson.getWeekNum())
    18. &&ObjectUtil.equal(scheduleLesson.getLessonCode(),reqLesson. getLessonCode())));
    19. ScheduleLesson obj=new ScheduleLesson();
    20. BeanUtils.copyProperties(reqLesson, obj);
    21. scheduleLessons.add(obj);
    22. //更新内容
    23. update.set("gradeTimetables.$.scheduleLessons", scheduleLessons);
    24. mongoTemplate. updateFirst(upQuery,update,mongoTemplate.getCollectionName(TimetableD0.class));
    25. }
    26. else {
    27. criteria = new Criteria();
    28. criteria. and("_id").is(new 0bjectId(vo.getTimetableId()))
    29. .and("gradeTimetables.gradeCode").is(vo.getGradeCode());
    30. upQuery = Query.query(criteria);
    31. update.addToSet("gradeTimetables.$.scheduleLessons", reqLesson);
    32. mongoTemplate.updateMulti(upQuery,update, mongoTemplate.getCollectionName(TimetableD0.class));
    33. }

    查询比较简单就不写了;可以搜索其他文章。

  • 相关阅读:
    成人职业教育:知乎、B站、网易“短兵相接”
    程序员的画图工具-代码画图的美人鱼mermaid
    JAVA JVM 是怎么判定对象已经“死去”?
    STM32L4R9ZIY6P 高性能嵌入式-MCU 微控制器
    TCL基础学习 -输出 赋值 替换和数学表达
    C++ 实现定时器的两种方法(线程定时和时间轮算法修改版)
    Node当中的事件循环
    JavaWeb、终章案例
    智能家居系统
    【算法优选】双指针专题——壹
  • 原文地址:https://blog.csdn.net/qq_43511677/article/details/127092036