2016-11-16 3 views
0

Может ли кто-нибудь показать мне представление Spring ниже запроса.Весна Совокупное представление запроса mongodb

db.groupsDocument.aggregate(
{$unwind:"$groups"}, 
{$match:{"groups.students":"8b8a7464-4dff-4136-ab0f-ec2bfe1ec48e"}}, 
{$group:{ _id:"$_id",groups:{$push:"$groups"},createdDate:{$first:"$createdDate"},editedDate:{$first:"$editedDate"},editedBy:{$first:"$editedBy"}}}) 

Выше запрос - рабочий файл.

Я попытался под кодом, но он не работает. Он бросает ошибку «Нет свойства _id, найденного для типа GroupDocument!»

GroupOperation groupOperation=Aggregation.group("$_id").push("$groups").as("groups").first("$createdDate").as("createdDate") 
         .first("$editedDate").as("editedDate") 
         .first("$editedBy").as("editedBy"); 

Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.unwind("$groups"), 
        Aggregation.match(where("_id.teacherId").is("5").and("groups.students").in("11")), 
        groupOperation); 

AggregationResults<BasicDBObject> groupResults = groupsMongoTemplate.aggregate(aggregation, 
        GroupsDocument.class, BasicDBObject.class); 

Мой идентификатор в документе, содержит два поля, как показано ниже

"_id" : { "teacherId" : "1", "Year" : "2016" } 

структуры документа

{ 
    "_id" : { "teacherId" : "1", "Year" : "2016" }, 
    "groups" : [ { 
     "groupId" : "123", 
     "groupName" : "Test1", 
     "groupNameLowerCase" : "test1", 
     "description" : "sample document", 
     "students" : ["11", "22"] 
     }, 
    { 
     "groupId" : "234", 
     "groupName" : "Test2", 
     "groupNameLowerCase" : "test2", 
     "description" : "sample document", 
     "students" : ["11", "22"] 
     }, 
     { 
     "groupId" : "345", 
     "groupName" : "Test3", 
     "groupNameLowerCase" : "test3", 
     "description" : "sample document", 
     "students" : ["21", "32"] 
     } 
    ], 
    "editedBy" : "sachin", 
    "createdDate":"11/11/2016" 
    "editedDate":" 11/14/2016" 

} 

КЛАСС:

@Document 
public class GroupsDocument extends AbstractDocument { 

    /** 
    * document _id and shard key 
    * 
    * composite key: Teacherid, Year 
    */ 
    @Id 
    @Field(FieldDefinition.DOCUMENT_ID) 
    private final GroupsDocumentId GroupsDocumentId; 

    @Field(FieldDefinition.GROUPS) 
    private final Collection<Group> groups; 

    @Field(GroupsDocument.FieldDefinition.CREATED_DATE) 
    private final Date createdDate; 

    @Field(GroupsDocument.FieldDefinition.EDITED_DATE) 
    private Date editedDate; 

    @Field(GroupsDocument.FieldDefinition.EDITED_BY) 
    private String editedBy; 

    /** 
    * empty constructor 
    */ 
    @SuppressWarnings("unused") 
    public GroupsDocument() { 
     this(null, null, Collections.emptyList(), null, null); 
    } 


    public GroupsDocument(String teacherId, String year, Collection<Group> groups, String editedBy) { 
     this(teacherId, year, groups, new Date(), editedBy); 
    } 

    public GroupsDocument(
      String teacherId, String year, Collection<Group> groups, Date createdDate, String editedBy) { 
     this.GroupsDocumentId = new GroupsDocumentId(teacherId, year); 
     this.groups = groups; 
     this.createdDate = createdDate; 
     this.editedDate = this.createdDate; 
     this.editedBy = editedBy; 
    } 

    public GroupsDocumentId getGroupsDocumentId() { 
     return GroupsDocumentId; 
    } 

    public Collection<Group> getGroups() { 
     return groups; 
    } 

    public Date getEditedDate() { 
     return editedDate; 
    } 

    public Date getCreatedDate() { 
     return createdDate; 
    } 

    public void setEditedDate(Date editedDate) { 
     this.editedDate = editedDate; 
    } 

    public String getEditedBy() { 
     return editedBy; 
    } 

    public void setEditedBy(String editedBy) { 
     this.editedBy = editedBy; 
    } 

Id класса:

public class GroupsDocumentId extends AbstractDocument { 

    @Field(GroupsDocument.FieldDefinition.teacherId) 
    private final String teacherId; 

    @Field(GroupsDocument.FieldDefinition.year) 
    private final String year; 

    /** 
    * empty constructor 
    */ 
    @SuppressWarnings("unused") 
    public GroupsDocumentId() { 
     this(null, null); 
    } 

    public GroupsDocumentId(String teacherId, String year) { 
     this.teacherId = teacherId; 
     this.year = year; 
    } 

    public String getteacherId() { 
     return teacherId; 
    } 

    public String getyear() { 
     return year; 
    } 
+0

Можете ли вы добавить класс группы документов и образец образца для тестирования? – Veeram

+0

Это тот самый, который вы ответили вчера. Почему-то это не для меня весна. Http://stackoverflow.com/questions/40625566/how-to-filter-array-in-mongodb-document-using-spring – Sachin

+0

О, ладно. Можете ли вы добавить класс группового документа? похоже, что он не работает при отображении поля идентификатора. – Veeram

ответ

0

Изменить личные окончательные группыDocumentId GroupsDocumentId для частных окончательных группDocumentId _id для контекста весеннего сопоставления для привязки переменной id к типу GroupDocumentId в классе GroupsDocument.

В качестве альтернативы вы можете использовать этот агрегатный вариант для обхода проверки типов.

AggregationResults<BasicDBObject> groupResults = mongoTemplate.aggregate(aggregation, 
      "groupsDocument, BasicDBObject.class); 
+0

Он начал работать после изменения имени свойства id на _id. Даже я могу напрямую получить список объектов GroupDocument вместо объектов BasicDBObject. Но в результате _id приходит как null. все остальные поля отображаются правильно, но _id не отображается. Когда я использую BasicDBObject, тогда в отображаемом результате я получаю teacherid и год как два отдельных поля. Код похож на List result = groupResults.getMappedResults(); – Sachin

Смежные вопросы