I am using the mongodb-driver-sync
library, version: 4.2.3
in my Java project to insert values into a MongoDB collection. When I insert them, the field names are not the values in the @BsonProperty
annotation but the lower camel case of the Java variable names. How do I make it use my annonation value?
My POJO is:
public class Product { private ObjectId id; @BsonProperty(value = "product_sk") private String ProductSK; @BsonProperty(value = "product_id") private String ProductID; @BsonProperty(value = "upc") public String UPC; public ObjectId getId() { return id; } public Product setId(ObjectId id) { this.id = id; return this; } public String getProductSK() { return ProductSK; } public Product setProductSK(String productSK) { ProductSK = productSK; return this; } public String getProductID() { return ProductID; } public Product setProductID(String productID) { ProductID = productID; return this; } public Product setUPC(String uPC) { UPC = uPC; return this; } }
My insertion code is:
public void insertProduct(List<Product> products) { ConnectionString connectionString = new ConnectionString(MONGO_URI); CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build()); CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry); MongoClientSettings clientSettings = MongoClientSettings.builder() .applyConnectionString(connectionString) .codecRegistry(codecRegistry) .build(); try (MongoClient mongoClient = MongoClients.create(clientSettings)) { MongoDatabase db = mongoClient.getDatabase(DATABASE); MongoCollection<Product> productCollection = db.getCollection("products", Product.class); productCollection.insertMany(products); } }
The BSON entered is:
{ "_id" : ObjectId("60afb7be0af8954d7ce91b8f"), "productID" : "test1", "productSK" : 123, "uPC" : "test2" }
It should be:
{ "_id" : ObjectId("60afb7be0af8954d7ce91b8f"), "product_id" : "test1", "product_sk" : 123, "upc" : "test2" }
My dependencies are:
implementation 'com.google.code.gson:gson:2.8.6' implementation group: 'org.mongodb', name: 'mongodb-driver-sync', version: '4.2.3' implementation group: 'org.mongodb', name: 'mongodb-crypt', version: '1.2.0'
Advertisement
Answer
Maybe it is a matter of convention. Your properties all start with capital letters. Since getter/setter convention advise that this kind of property should start with low case letters I would try something like this:
private ObjectId id; @BsonProperty(value = "product_sk") private String productSK; // instead of ProductSK @BsonProperty(value = "product_id") private String productID; // instead of ProductID @BsonProperty(value = "upc") public String upc; // or uPC