SpringData Mongo에서 기준 쿼리를 사용하여 결과를 가져 오는 동안 문서의 필드 중 하나를 업데이트합니다.

카르 틱

기준 쿼리를 사용하여 MongoDB에서 문서를 가져옵니다. 여기서 내 요구 사항은 SpringData Mongo의 Criteria를 사용하여 하위 문서를 쿼리하여 부모 문서 값에서 필드를 업데이트하려는 것입니다. 상위 문서는 주석이고 중첩 된 문서는 회신입니다. 아래 코드를 사용하여 하위 문서와 함께 주석 목록을 얻을 수 있습니다.

Data Set:
{
"_id" : ObjectId("5cb726937a7148376094d393"),
"_class" : "vzi.cpei.Comments",
"text" : "first comment on money control",
"replies" : [        
    {
        "_id" : "3cfef1cd-e0da-4883-86a4-17b223639087",
        "text" : "extract the traces",
        "status" : true
    },
    {
        "_id" : "3cfef1cd-e0da-4883-86a4-17b153690087",
        "text" : "replied deiberate",
        "status" : false
    },
    {
        "_id" : "3cfef1cd-e0da-4883-86a4-17b153139087",
        "text" : "Bgm",
        "status" : true
    }],
}
Response DTO:
      
      public class CommentsDTO{
      private String id;
      private String text;
      private List<Replies> replies;
      private Integer totalReplies;
    }

Spring 데이터 mongo Criteria 쿼리를 사용하여 Spring에서 작성한 코드,

    Query query = new Query();
    Criteria criteria =Criteria.where("_id").is(new ObjectId("5efe3d1f8a2ef008249f72d9"));
    query.addCriteria(criteria);
    List<Comments> comments = mongoOps.find(query,"Comments", 
  CommentsDTO.class);
    return comments;

결과적으로 repliesCount 필드를 true 상태의 총 응답 수로 업데이트하여 예상 출력이 다음과 같아야합니다.

{
"_id" : ObjectId("5cb726937a7148376094d393"),
"_class" : "vzi.cpei.Comments",
"text" : "first comment on money control",
"totalReplies" : 2
"replies" : [        
    {
        "_id" : "3cfef1cd-e0da-4883-86a4-17b223639087",
        "text" : "extract the traces",
        "status" : true
    },
    {
        "_id" : "3cfef1cd-e0da-4883-86a4-17b153690087",
        "text" : "replied deiberate",
        "status" : false
    },
    {
        "_id" : "3cfef1cd-e0da-4883-86a4-17b153139087",
        "text" : "Bgm",
        "status" : true
    }],
}

가져 오는 동안이 작업을 수행 할 위치가 완전히 혼란 스럽습니다.

Valijon

MongoDB 집계 를 수행해야합니다 .

설명 pipeline

  1. $match결과를 필터링하기 위해 단계를 적용합니다 (와 유사 .find(query)).
  2. 를 적용하여 $project문서 구조를 변환하고 값을 totalReplies기반으로 계산 된 필드를 포함 replies합니다.

껍질

db.Comments.aggregate([
  {
    $match: {
      "_id": ObjectId("5cb726937a7148376094d393")
    }
  },
  {
    $project: {
      _class: 1,
      replies: 1,
      totalReplies: {
        $size: {
          "$filter": {
            input: "$replies.status",
            as: "status",
            cond: "$$status"
          }
        }
      }
    }
  }
])

몽고 놀이터

봄-몽고

import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
...

Aggregation agg = Aggregation.newAggregation(
        match(Criteria.where("_id").is(new ObjectId("5cb726937a7148376094d393"))),
        project("_id", "_class", "replies").and(ArrayOperators.Size.lengthOfArray(
                ArrayOperators.Filter.filter("replies.status").as("filter").by("$$filter")
                )).as("totalReplies"));

//System.out.println(agg);
return mongoOps.aggregate(agg, mongoOps.getCollectionName(CommentsDTO.class), CommentsDTO.class);

편집 : 레거시 Spring-boot 1.4.2

project("_id", "_class", "replies")
        .and(AggregationFunctionExpressions.SIZE
            .of(new BasicDBObject("$filter",
                new BasicDBObject("input", "$replies.status")
                    .append("as", "status")
                    .append("cond", "$$status"))))
        .as("totalReplies")

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관