4

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?

Ramya
  • 1,067
  • 6
  • 16
  • 29

3 Answers3

9

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);
Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
3

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

Community
  • 1
  • 1
shelman
  • 2,689
  • 15
  • 17
0

...and this is how to do it with mongo-driver version >= 3.1 (mine is 3.2.2):

    Document tenant = new Document("Tenant_Id", 2)
            .append("Tenant_Info", "check")
            .append("Prop_Info", "client");

    Bson filter = Filters.eq( "System_Info", "...." ); //get the parent-document
    Bson setUpdate = Updates.push("Tenant", tenant);

    coll.updateOne(filter, setUpdate);

Hope that helps someone.

OhadR
  • 8,276
  • 3
  • 47
  • 53