简体   繁体   中英

guarantee fields order in a mongodb documents using mongodb java driver

Using MongoDB driver 4.1.0 (and quarkus 1.1.1), I have an entity with a composite _id :

@BsonId
@JsonProperty("_id")
private CompositeId id = new CompositeId();

@Data
@AllArgsConstructor
@NoArgsConstructor
public static class CompositeId {
    @BsonProperty("b")
    private int b;
    @BsonProperty("a")
    private String a;
}

(where a is actually an ObjectId hex string)

After saving the entity, the _id fields are preserved in an alphabetic order:

"_id" : {
    "a" : "61a480509da3560292eb1ab5",
    "b" : 1234
},

Later, the same logical entity is upserted elsewhere using pymongo :

collection.update_one({'_id': id}, {'$set': ...

The id in the query document is constructed with python OrderedDict , with b as first in order, and a as second.

So I end up with two identical documents in collection, differ only in _id fields order:

{
    "_id" : {
        "a" : "61a480509da3560292eb1ab5",
        "b" : 1234
    },
    // rest of identical fields for Java inserted document
}
{
    "_id" : {
        "b" : 1234,
        "a" : "61a480509da3560292eb1ab5"
    },
    // rest of identical fields for Python upserted document
}

So, my question is, is there a way to configure the Java driver to preserve the order of fields in document (something such as @JsonPropertyOrder ) or less realistically, using quarkus/panache configuration?

Constructing a Bson document did the trick:

Document id = new Document();
id.append("b", 1234);
id.append("a",  new ObjectId().toHexString());
Document entity = new Document("_id", id);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM