javamongodb

MongoDB is Forcibly Renaming a field called id in data to _id


I have a simple POJO class as below, with a field called 'id'

public class AssemblyMenuModel {
    
    @JsonProperty("caption")
    protected String caption;

    @JsonProperty("path")
    protected String path;

    @JsonProperty("id")
    protected String id;

    @JsonProperty("name")
    protected String name;

    @JsonProperty("menus")
    protected List<AssemblyMenuModel> menus;

}

When I insert a record of the above, the 'id' attribute is being forcibly named to '_id' by MongoDB. While I understand the significance of '_id' attribute; I could not find any documentation as to why the id field is being renamed to _id during document insertions; any explanation would be appreciated.

Is there any way to stop this behaviour?

EDIT - 1

The blow routine inserts the value in a map in the document

public void setConfigValue(String cfgName, Object cfgValue) {

        System.out.println("setConfigValue :: Setting config value");
        
        if(cfgName==null || cfgName.isEmpty())return;
        
        try {
            
            Document cfgDocument=getAppConfigDoc();

            System.out.println("setConfigValue :: Config document = "+cfgDocument);
            
            if(cfgDocument!=null) {
                
                String appId=PlatformContextInfoProvider.getAppIdentifier();
                Bson filter=Filters.eq("applicationIdentifier", appId);
                
                UpdateOptions options=new UpdateOptions();
                options.upsert(false);
                
                Bson update=Updates.set("configs."+cfgName, cfgValue);
                getCollection().updateOne(filter, update, options);
                
            }//if closing
            
        }catch(Exception e) {e.printStackTrace();}
        
    }//setAppConfig closing

The entire document in MongoDB looks like below after insertion MongoDB Document


Solution

  • This is because MongoDB Driver by default map id to _id, when we use CodecRegistry with PojoCodecProvider.

    We can use the @BsonProperty annotation alongside the @JsonProperty annotation on the id field to ensure MongoDB and JSON processing libraries handle it as a custom document field rather than the default _id identifier, find more details here.

    In this case converting the POJO class like below will solve the problem

    public class AssemblyMenuModel {
        
        @JsonProperty("caption")
        protected String caption;
    
        @JsonProperty("path")
        protected String path;
    
        @BsonProperty("id") //MongoDB interprets this as "id" 
        @JsonProperty("id") //Jackson interprets this as "id"
        protected String id;
    
        @JsonProperty("name")
        protected String name;
    
        @JsonProperty("menus")
        protected List<AssemblyMenuModel> menus;
    }