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?

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

check here for the explanation of the update fields. mongodb.org/display/DOCS/Updating#Updating-update%28%29
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.