在MongoDB中更新嵌套数组文档 [英] Updating nested array document in MongoDB

查看:178
本文介绍了在MongoDB中更新嵌套数组文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个像这样的mongo文档,我需要根据val更新数组

So I have a mongo document like this and i need to update the array based on the val

{
"_id" : NumberLong(222),
"pattern":"grain"
"BASIC" : {
    "frame":"clear"
    "tin" : [ 
        {
            "val" : "abc",
            "unit" : NumberLong(2311)
        }, 
        {
            "val" : "def",
            "unit" : NumberLong(2311)
        }, 
    ]
}
}

这是我尝试过的代码

        collection = db.getCollection("test");
    Bson where = new Document().append("_id", 222).append("BASIC.tin.val","abc");

     Bson update = new Document()
                .append("BASIC.tin.$.val", "xyz");
     Bson set = new Document().append("$set", update);
        try {

            UpdateResult result = collection.updateOne(where , set, new UpdateOptions().upsert(true));

            if(result.getMatchedCount()>0){
                System.out.println("updated");
                System.out.println(result.getModifiedCount());
            }else{
                System.out.println("failed");
            }
        } catch (MongoWriteException e) {
          e.printStackTrace();
        }

更新工作正常,但如果发现失败,则不会更新 这是我得到的错误:

update works fine but does not upsert if the find fails This is the error which i get:

com.mongodb.MongoWriteException:位置运算符未从查询中找到所需的匹配项.未扩展的更新:BASIC.tin.$.val 在com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:558) 在com.mongodb.MongoCollectionImpl.update(MongoCollectionImpl.java:542)

com.mongodb.MongoWriteException: The positional operator did not find the match needed from the query. Unexpanded update: BASIC.tin.$.val at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:558) at com.mongodb.MongoCollectionImpl.update(MongoCollectionImpl.java:542)

推荐答案

无法在嵌入式文档中进行向上插入,因此会出现错误.因此,要模拟嵌入式文档的upsert,您需要像下面那样更新代码.这将检查修改后的计数,如果其值为0,则意味着我们需要在嵌入式文档中插入一个新文档,并为此使用push.对于您拥有的示例文档,这将使用"pqr"作为val和"unit"作为400进行upsert.

The upsert into the embedded documents is not possible and hence the error. So to simulate upsert for embedded documents, you'll need to update your code like below. This checks for the modified count and if its 0 then it means we need to insert a new document in the embedded documents which makes use of push for this. This will do an upsert with "pqr" as val and "unit" as 400 for the example docs you have.

Bson where = new Document().append("_id", 222).append("BASIC.tin.val","pqr");

Bson update = new Document()
        .append("BASIC.tin.$.val", "xyz");
Bson set = new Document().append("$set", update);

try {

    UpdateResult result = collection.updateOne(where , set, new UpdateOptions());

    if(result.getModifiedCount() > 0){
        System.out.println("updated");
    } else if(result.getModifiedCount()==0){
          System.out.println("upserting");
          Bson where1 = new Document().append("_id", 222);
          Bson upsert = new Document().append("BASIC.tin", new Document().append("val", "pqr").append("unit", 400));;
          Bson push = new Document().append("$push", upsert);
          UpdateResult result1 = collection.updateOne(where1 , push, new UpdateOptions());
          if(result1.getModifiedCount() == 1)
              System.out.println("upserted");
    }else {
        System.out.println("failed");
    }
} catch (MongoWriteException e) {
  e.printStackTrace();
}

插入后的样本响应

{
    "_id": NumberLong(222),
    "pattern": "grain",
    "BASIC": {
        "frame": "clear",
        "tin": [{
            "val": "xyz",
            "unit": NumberLong(2311)
        }, {
            "val": "def",
            "unit": NumberLong(2311)
        }, {
            "val": "pqr",
            "unit": 400
        }]
    }
}

这篇关于在MongoDB中更新嵌套数组文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆