ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

如何使用Java在MongoDB中的嵌套数组中添加元素

2019-11-19 22:04:26  阅读:380  来源: 互联网

标签:mongodb mongodb-query java


大家好,我正在用Java开发mongodb,我有一个场景,如果外部文档匹配,那么我必须在嵌套数组中更新/添加计数,例如,我想做这样的事情:

`"_id" : ObjectId("55d71603aed7562284e5df95"),
"id" : "1",
"type" : "a",
"score" : {
        "mark1" : "1",
        "mark2" : "2",
        "count" : { "one","two"                
        }
}`

如果我再次发送具有相同字段的文档,例如id:1,请输入:a,mark1:1,mark2:2,那么我必须将我的文档作为

`"_id" : ObjectId("55d71603aed7562284e5df95"),
"id" : "1",
"type" : "a",
"score" : {
        "mark1" : "1",
        "mark2" : "2",
        "count" : { "one","two","three"                
        }
}`

但是我得到这样的东西:

`"_id" : ObjectId("55d71e42aed7560e8c9d02e4"),
"id" : "1",
"type" : "a",
"score" : {
        "mark1" : "1",
        "mark2" : "2",
        "count" : {
                "count" : "one",

        }
}`

我的java代码是

 `mongoDatabase=mongoClient.getDatabase("TestNestedInsert");
        Document sourceDocument=mongoDatabase.getCollection("entity").find(new Document("id",1).append("score.mark1", "1").append("score.mark2", "2")).first();
        if(sourceDocument==null){
            Document entity=new Document();
            entity.append("id", "1");
            entity.append("type", "a");
            entity.append("score", new Document("mark1","1").append("mark2", "2").append("count", new Document("count","one")));
            mongoDatabase.getCollection("entity").insertOne(entity);
        }
        else{
            mongoDatabase.getCollection("entity").findOneAndUpdate(new Document("id",1).append("score.mark1", "1").append("score.mark2", "2"), new Document("$set",new Document("score.count","three")));
        }
        ` 

我知道我们不能有重复的键,我也尝试过$set和$push,但是我被卡住了.有什么帮助吗?

解决方法:

根据代码,主要问题在于“ count”键是一个对象而不是数组.因此正确的JSON表示为:

{
    "_id": ObjectId("55d71603aed7562284e5df95"),
    "id": "1",
    "type": "a",
    "score": {
        "mark1": "1",
        "mark2": "2",
        "count": [
            "one",
            "two",
            "three"
        ]
    }
}

请注意“计数”键后面的方括号“ []”.

关于新的mongo java驱动程序(3.0),我有相同的问题.
这是我解决的方法:

MongoDatabase mongoDatabase = mongoClient.getDatabase("TestNestedInsert");
MongoCollection<Document> entityCollection = mongoDatabase.getCollection("entity");

Document queryDocument = new Document("id", 1).append("score.mark1", "1").append("score.mark2", "2");
Document sourceDocument = entityCollection.find(queryDocument).first();

if (sourceDocument == null) {
    Document entity = new Document();
    entity.append("id", "1");
    entity.append("type", "a");

    // Create the score nested object
    String[] countArray = { "one", "two" }; // create the count array
    Document scoreObject = new Document()
            .append("mark1", "1")
            .append("mark2", "2")
            .append("count", countArray); // append the count array

    entity.append("score", scoreObject); // append the score object.
    entityCollection.insertOne(entity);
}
else{
    // push the new element to the count array.
    // see: https://docs.mongodb.org/v3.0/reference/operator/update/push/#append-a-value-to-an-array
    Document elementToArray = new Document("score.count", "three");
    Document pushElement = new Document("$push", elementToArray);
    entityCollection.updateOne(queryDocument, pushElement);
}

希望能帮助到你!

标签:mongodb,mongodb-query,java
来源: https://codeday.me/bug/20191119/2039242.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有