0

我有一个包含嵌入式文档的集合。

 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_Id 中的字段 Tenant_Info 并将其设置为“失败”:2

我需要使用 mongodb java 来完成。我知道在租户数组中插入另一个租户信息。但在这里我需要使用 java 代码设置字段。

谁能帮我做到这一点?

4

1 回答 1

3

像这样的东西怎么样(未经测试):

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

Tenant_id对于所有顶级文档,它应该将集合中的第一个嵌套文档更新为 2。如果您需要定位特定的顶级文档,则需要将其添加到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);
于 2012-09-06T20:09:36.933 回答