2012-09-06 53 views
0

我有一个包含嵌入文档的集合。Mongodb更新和设置嵌入文档中的字段

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: ... 
        } ] 
        }} 

我需要更新和设置字段Tenant_Info在Tenant_Id为 “失败”:2

我需要使用MongoDB的Java来做到这一点。我知道在租户数组中插入另一个租户信息。但在这里我需要使用java代码设置字段。

任何人都可以帮助我做到这一点?

+0

是为了读作系统的第一行:'(用冒号) - 即它是一个字段在文档中或系统集合的名字吗? – theon

回答

3

如何像这样(未经):

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

应该对所有顶级文件更新集合中的第一个嵌套的文件为2的Tenant_id。如果您需要定位特定顶级文档,则需要将其添加到update调用中第一个对象参数的as字段。

而且在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); 
+0

以供将来参考,添加定位顶层文件:db.coll.update( { “System.system_type.Tenant.Tenant_Id”:2, “SYSTEM_INFO”: “手动” },{ $ 设置:{ “System.system_type.Tenant。$。Tenant_Info”:“failed” } }, false, true ); –