Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 528
Ramya Avatar asked Dec 16 '22 19:12

Ramya


2 Answers

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);
like image 102
Parvin Gasimzade Avatar answered Jan 15 '23 18:01

Parvin Gasimzade


Are you trying to add another Tenant into the array? If so, you would want to create a DBObject representing the Tenant, and then $push it onto the array.

In Java, embedded documents are represented by DBObjects (of which BasicDBObject is a subclass). Here is an example of inserting an embedded document, from the docs:

http://www.mongodb.org/display/DOCS/Java+Tutorial#JavaTutorial-InsertingaDocument

Additionally, here is an example of using $push in Java:

Updating an array in MongoDB using Java driver

like image 26
shelman Avatar answered Jan 15 '23 18:01

shelman