Spring Boot Integration Integration --MongoDB. 4 (MongoDB MongoDB packets associated to a weight table and a query)

Previous article

About Version

rely version
springboot 2.0.8.RELEASE
mongodb 4.0.14

This content just to introduce mongodb most basic use and configuration, as a well-known database, its existence a considerable number of advanced usage, start to introduce content to be large, of course, I am not the god of related fields, the following content is just finishing his Some accumulation of daily use. It is the accumulation of their own experience, but also want to help the students later

About the project

This content is what I try to finishing work in contact with the various tools used in the method in springboot. All the methods described below have been provided a test case. Because each example involves more code, so the article posted only part of the code. All code here: https: //gitee.com/daifyutils/springboot-samples.

United-table query

Simple contingency table query

mongodb multi-table queries using the Aggregation.lookupAPI to operate. The methods lookup(String from, String localField, String foreignField, String as)four parameter tables are connected to the main field in the table need to connect the field is connected to the table, and the data after the connection is mapped to a field in the result set.

The following is a simple contingency table query, the Ordertables userIdand UserInfotable id field associating queried UserInfosave the information to the result set userInfofield.

    @Override
    public List<OrderVo> queryOrderAndUserInfo() {

        Criteria criteria = new Criteria();
        MatchOperation match = Aggregation.match(criteria);
        // 和另外一个集合进行关联,将其作为其属性
        LookupOperation lookup = Aggregation.lookup("UserInfo",// 连接表
            "userId",// 查询表中字段
            "_id",// 连接表中字段
            "userInfo");// 返回数据所在的属性名称
        TypedAggregation<Order> noRepeatAggregation2 =
            Aggregation.newAggregation(Order.class,match,lookup);

        AggregationResults<OrderVo> noRepeatDataInfoVos2 = mongoTemplate.aggregate(noRepeatAggregation2, OrderVo.class);
        List<OrderVo> noRepeatDataList2 = noRepeatDataInfoVos2.getMappedResults();
        return noRepeatDataList2;
    }

United table lookup - operate on the data to be coupled

When connecting two data tables, data is mapped onto a property below. Structure similar to the following format.

{
    "field":"value",
    "field2":"value2",
    "field3":"value3",
    "被映射的属性" : {
        "field":"value",
        "field2":"value2"
    }
}

For the above, we can use this format object.objectdirectly access nested incoming data, while some polymerization or sorting or filtering operation on its contents.

The following example is completed Orderand UserInfothe associated tables, UserInfothe data set is nested in a userInfocase attribute, then userInfo.typeaccess to UserInfothe typeproperty, and sorted based on their content.

    @Override
    public List<OrderVo> queryOrderAndUserInfoSort(Sort.Direction direction) {
        Criteria criteria = new Criteria();
        MatchOperation match = Aggregation.match(criteria);
        // 和另外一个集合进行关联,将其作为其属性
        LookupOperation lookup = Aggregation.lookup("UserInfo",
            "userId",// 查询表中字段
            "_id",// 连接表中字段
            "userInfo");// 返回数据所在的属性名称
        SortOperation sort =
            Aggregation.sort(new Sort(direction,"userInfo.type"));
        TypedAggregation<Order> noRepeatAggregation2 =
            Aggregation.newAggregation(Order.class,match,lookup,sort);

        AggregationResults<OrderVo> noRepeatDataInfoVos2 = mongoTemplate.aggregate(noRepeatAggregation2, OrderVo.class);
        List<OrderVo> noRepeatDataList2 = noRepeatDataInfoVos2.getMappedResults();
        return noRepeatDataList2;
    }

Expand the nested structure

For connecting many relationship exists, the data is placed in a connection will be set, this can be used when Aggregation.unwindthe data expansion. The example above, add the following statement to say that UserInfosthe field contents expand

Aggregation.unwind("UserInfos")
  • Structure before expansion
{
    "field":"value",
    "UserInfos" : [{"field":"value1"},{"field":"value2"}]
}
  • Structure after expansion
{
    "field":"value",
    "UserInfos" : {"field":"value1"}
}
{
    "field":"value",
    "UserInfos" : {"field":"value2"}
}

ps. Note that the code I did not realize their test code. If the need to test its deployed effects, it returns to redefine the object structure.

United query table - adjusted data names are linked

Sometimes when we use multi-table associated with the use of a separate layer of the object data to receive data on the code level nested data structures may not be too convenient that we use. This time we can cooperate on the introduction of articles Aggregation.projectto change its data structures. Last article I introduced her name can be used to modify the data, the following is a way to modify the data structure. The following example will userInfo.userNamepoint to userNamein the operation such userNameas a nested attribute data will be modified as the data in the root node displayed.

    @Override
    public List<OrderAndUserVo> queryOrderUserInfo() {
        Criteria criteria = new Criteria();
        MatchOperation match = Aggregation.match(criteria);
        // 和另外一个集合进行关联,将其作为其属性
        LookupOperation lookup = Aggregation.lookup("UserInfo",// 连接表
            "userId",// 查询表中字段
            "_id",// 连接表中字段
            "userInfo");// 返回数据所在的属性名称
        Field userName = Fields.field("userName", "userInfo.userName");
        ProjectionOperation project = Aggregation.project("id","totalMoney","totalProduct","userId","type")
            .andInclude(Fields.from(userName));
        TypedAggregation<Order> noRepeatAggregation2 =
            Aggregation.newAggregation(Order.class,match,lookup,project);

        AggregationResults<OrderAndUserVo> noRepeatDataInfoVos2 = mongoTemplate.aggregate(noRepeatAggregation2, OrderAndUserVo.class);
        List<OrderAndUserVo> noRepeatDataList2 = noRepeatDataInfoVos2.getMappedResults();
        return noRepeatDataList2;
    }

Packet de-duplication

We use the Aggregation.grouppacket data can be achieved, but sometimes we want to know the contents of duplicate data deduplication when there are several duplicate data query under different conditions.

For example, we will be a different customer (user) of the order (order) is divided into different types (type), and now we want to know different customers different types exist in the end, by grouping the "userId" and "type" we only different users can get different order type polymerization results. Of course, we may be cyclic code obtained as a result of different users (user) in the end comprises several number (type) of. But this leads to the logical split into the program code and data queries.

Introduced before the polymerization is actually a conduit pipe, the pipe after the data processing is a result of treatment before passing duct. To solve the packet deduplication or want to use the characteristics of its pipes. Such as the above described results we obtained by dividing "userId" and "type" is the following

userId type count
1 1 This userId this type include the amount of data
1 2 This userId this type include the amount of data
2 1 This userId this type include the amount of data
2 2 This userId this type include the amount of data
2 3 This userId this type include the amount of data

At this point we can not know every userId in the end there is much different type. But we follow the pipeline can be grouped again on the above data.

We packet again, this time using userIdthe packet data is performed, the final count is to get the sum of the value type, this time to get the result shown below is the final result.

userId count
1 This type contains the number of userId
2 This type contains the number of userId

Code

The above code is the use of a logic following.

    @Override
    public List<GroupVo> getAggGroupDeDuplication() {
        // 根据用户id和type进行分组
        GroupOperation operation1 = Aggregation.group( "userId","type");
        // 对上面的结果再次分组可以获得userId的type数据
        GroupOperation operation2 = Aggregation.group("userId").count().as("count");

        TypedAggregation<Order> noRepeatAggregation =
            Aggregation.newAggregation(Order.class,operation1,operation2);
        AggregationResults<GroupVo> noRepeatDataInfoVos = mongoTemplate.aggregate(noRepeatAggregation, GroupVo.class);
        List<GroupVo> noRepeatDataList = noRepeatDataInfoVos.getMappedResults();
        System.out.println(JSON.toJSONString(noRepeatDataList));
        return noRepeatDataList;
    }

Limited personal level, the contents of the above description may exist where there is no clear or wrong, if the development of the students found, please let me know, I will first modify content, I hope you see buried in the New Year can only house the home case code code hard to force, give meLike a point. Your praise is my point forward momentum. Here I wish you all a happy New Year.

Published 204 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/qq330983778/article/details/104079857