Search code examples
javamongodbspring-dataspring-batchspring-mongodb

MongoTemplate deterministic order in update query


I am using MongoTemplate in my Spring Batch writer, and I would like to use an $addToSet operator to push my elements in an array only if they do not exist yet. I see in the Mongodb documentation that the $addToSet works only if the fields are in the same order.

So my question is: does MongoTemplate convert my pojo into Bson document always in the same order?

I found this converter in MongoTemplate's code (MappingMongoConverter), and to me the loop is not deterministic :

private void writeProperties(Bson bson, MongoPersistentEntity<?> entity, PersistentPropertyAccessor<?> accessor,
        DocumentAccessor dbObjectAccessor, @Nullable MongoPersistentProperty idProperty) {

    // Write the properties
    for (MongoPersistentProperty prop : entity) {

        if (prop.equals(idProperty) || !prop.isWritable()) {
            continue;
        }
        if (prop.isAssociation()) {
            writeAssociation(prop.getRequiredAssociation(), accessor, dbObjectAccessor);
            continue;
        }

        Object value = accessor.getProperty(prop);

        if (value == null) {
            continue;
        }

        if (!conversions.isSimpleType(value.getClass())) {
            writePropertyInternal(value, dbObjectAccessor, prop);
        } else {
            writeSimpleInternal(value, bson, prop);
        }
    }
}

Solution

  • Spring Mongo @Field annotation allow to set explicitly the order of each field.

    Some of my POJOs have 1000 fields, it's a laborious solution in my case but is is a solution. If someone knows an easier way, I will be grateful :)

    source : https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/mapping/Field.html