如何通过java将json数据推送到MONGO DB中的arrya对象

时间:2015-11-24 07:14:45

标签: java json mongodb mongodb-query

 "termsrelation" : [ 
      {
        "rel": "RT",
        "terms": [
            {
                "objid": "55dc25083d2cbcb8b0dc48c8",
                "source": null,
                "scopeNote": [
                    {
                        "sourceType": "source",                    
                        "source": "abc"
                    }
                ],
                "formated_name": "Milkbuns",
                "name": "Milkbuns",
                "type": null,
                "url": "test.com",
                "nodeid": "14050"
            },
            {
                "objid": "552cae1940feb9123e3f5fb6",
                "source": null,
                "scopeNote": [
                    {
                        "sourceType": "source",                    
                        "source": "xyz"
                    }
                ],
                "formated_name": "Milkchocolate",
                "name": "Milkchocolate",
                "type": null,
                "url": "test.com",
                "nodeid": "193570"
            }
        ]
    }
]

我需要推

{
                            "sourceType" : "source",                            
                            "source" : "def"
                        }

json到scopeNote对象,其中name = Milkchocolate由java,请帮帮我

我使用搜索查询{ "$push" : { "termsrelation.$.terms.$.scopeNote" : { "sourceType" : "source" , "source" : "ddd" }}}尝试了此查询{ "$and" : [ { "id" : "4003"} , { "termsrelation.rel" : "RT"} , { "termsrelation.terms.scopeNote.sourceType" : "source"} , { "termsrelation.terms.scopeNote.source" : "xyz"} , { "termsrelation.terms.name" : "Milk chocolate"}]},但没有工作

1 个答案:

答案 0 :(得分:1)

步骤1.首先获取要插入的元素的位置

步骤2.您获得了职位

然后使用此查询

List<BasicDBObject> andQuery2 = new ArrayList<BasicDBObject>();
                andQuery2.add(new BasicDBObject("id", id));
                andQuery2.add(new BasicDBObject("termsrelation.rel", relation));
                andQuery2.add(new BasicDBObject("termsrelation.terms.name", name));

                BasicDBObject searchObj2 = new BasicDBObject();
                searchObj2.put("$and", andQuery2);

                BasicDBObject basicDBObject = new BasicDBObject();
                basicDBObject.put("sourceType", type);
                basicDBObject.put("source", source);                


                BasicDBObject updateQuery = new BasicDBObject();
                updateQuery.append("$push", new BasicDBObject().append("termsrelation.$.terms."+position+".scopeNote", basicDBObject));


                coll.update(searchObj2, updateQuery).getError();