Search code examples
mongodbmongodb-javamongodb-query

mongodb java to insert embedded document


I have a collection with embedded documents in it.

  System
  {
    System_Info: ...,

   Tenant: [ 
    { 
        Tenant_Id: ..., 
        Tenant_Info: ..., 
        Prop_Info: ...
    }, 
    { 
        Tenant_Id: ..., 
        Tenant_Info: ..., 
        Prop_Info: ...
    } ]

}

If I need to insert another tenant information like this

     Tenant { Tenant_Id:2,Tenant_Info:"check",prop_info:"client"}.

whats the mongodb query to insert embedded documents? and how to do it using java?


Solution

  • Use the following code to insert into array :

    BasicDBObject query = new BasicDBObject();
    query.put( "System_Info", "...." );
    
    BasicDBObject tenant = new BasicDBObject();
    tenant.put("Tenant_Id", 2);
    tenant.put("Tenant_Info", "check");
    tenant.put("Prop_Info", "client");
    
    BasicDBObject update = new BasicDBObject();
    update.put("$push", new BasicDBObject("Tenant",tenant));
    
    coll.update(query, update,true,true);