0

I have a collection with embedded documents.

 System
 {
     System_Info: "automated",

     system_type:
     {
         system_id:1,

          Tenant: [ 
                  { 
                Tenant_Id: 1, 
                Tenant_Info: "check", 
                Prop_Info: ...
                  }, 
                  { 
                 Tenant_Id: 2, 
                 Tenant_Info: "sucess", 
                  Prop_Info: ...
                  } ]
                  }}

I need to update and set the field Tenant_Info to "failed" in Tenant_Id: 2

I need to do it using mongodb java. I know to insert another tenant information in the tenant array. But here I need to set the field using java code.

Could anyone help me to do this?

theon
  • 14,170
  • 5
  • 51
  • 74
Ramya
  • 1,067
  • 6
  • 16
  • 29
  • Is the first line meant to read `System:` (with a colon) - i.e. it is a field in the document or is System the name of the collection? – theon Sep 06 '12 at 20:10

1 Answers1

3

How about something like this (untested):

db.coll.update(
    {
        "System.system_type.Tenant.Tenant_Id" : 2
    },
    {
        $set : {
            "System.system_type.Tenant.$.Tenant_Info" : "failed"
        }
    }, 
    false, 
    true
);

It should update the first nested document in the collection with a Tenant_id of 2 for all top level documents. If you need to target a specific top level document, you need to add it to the as field on the first object argument in the update call.

And the equivalent in Java:

BasicDBObject find = new BasicDBObject(
    "System.system_type.Tenant.Tenant_Id", 2
);

BasicDBObject set = new BasicDBObject(
    "$set", 
    new BasicDBObject("System.system_type.Tenant.$.Tenant_Info", "failed")
);

coll.update(find, set);
theon
  • 14,170
  • 5
  • 51
  • 74
  • for future reference, adding targeting top level document: db.coll.update( { "System.system_type.Tenant.Tenant_Id" : 2, "System_Info" : "manual" }, { $set : { "System.system_type.Tenant.$.Tenant_Info" : "failed" } }, false, true ); – Eyal Golan Jan 20 '15 at 23:02