The order fields of the Query statement generated by spring-data-mongodb are in the wrong order

Foreword:

Recently, when implementing a requirement, the data requested by the requirement needs to be sorted according to the playback volume and creation time. Considering that the playback volume and creation time may be the same, the sorting will be unstable, so Added "_id" as the third sorting field. When I was debugging, I found that the query statement generated by the Query object actually used "_id" as the first sorting field:

1. Query code:

        Query query = new Query();
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(Sort.Order.desc("aa"));
        orders.add(Sort.Order.desc("bb"));
        orders.add(Sort.Order.asc("_id"));
        query.with(Sort.by(orders));
        System.out.println(SerializationUtils.serializeToJsonSafely(query.getSortObject()));

2. The contents of the console output:

{ "_id" : 1, "aa" : -1, "bb" : -1 }

3. Debug screenshot:

 From the logic of the code, the correct query statement should be:

Sort: { "aa" : -1, "bb" : -1,"_id" : 1, }

But what we see is that "_id" is advanced:

Sort: { "_id" : 1, "aa" : -1, "bb" : -1 }

Cause Analysis:

1. Trace the code to see why such content is generated:

1) In the DocumentCodec.beforeFields method, if "_id" is found in the sorted field, write it first

2) In the DocumentCodec.skipField method, if "_id" is found in the sorted field, skip writing

After such a wave of magical operations, when we use SerializationUtils.serializeToJsonSafely(query.getSortObject()) to output the JSON format content of the sorting field, the "_id" field is adjusted to the first place.

Does it affect the query results?

When we saw that this Query was generated like this, our hearts tightened, what's going on? Difficulty Spring-data-mongodb can not achieve my appeal? Let's take a look at what the final statement sent to the MongoDB cluster looks like:

 Judging from the DEBUG in the above figure, the data sent to MongoDB is correct, and "_id" is not ranked first. After verifying the data in the collection, it is found that there is no problem.

in conclusion:

1. There is no problem in the execution of "_id" sorting

2. There is a problem with the "_id" sorting in the Query object generation toString method. It should be done deliberately. I don't know why

Guess you like

Origin blog.csdn.net/duzm200542901104/article/details/127922073