Java 对mongodb数据库进行修改

在json数据中,对数据进行追加,类似于追加产品评论

public String updateComment(Integer accountId,String _id,String goodsDescripe){
    List list = new ArrayList();
    Map map  = new HashMap();
    DBCollection dbCollection = mongoTemplate.getCollection("product_comment");
    if(_id!=null){
        BasicDBObject query2 = new BasicDBObject();
	    //new ObjectId(_id):是将String类型的id转换成Object
        query2.put("_id", new ObjectId(_id));
		//根据id查询语句
        DBObject dbObject = dbCollection.findOne(query2);
        if(dbObject!=null){
            BasicDBObject basicDBObject = (BasicDBObject)dbObject;
			//获取要修改的键里面的内容
            String replies1 = basicDBObject.getString("replies");
            Integer orderMainId = basicDBObject.getInt("orderId");
			//跨微服务获取内容
            String url = "http://QZH-ORDER/orderMain/getOrderMainId?orderMainId={orderMainId}";
            ResponseEntity responseEntity2 = restTemplate.getForEntity(url, QzhResult.class, orderMainId);
            if(responseEntity2.getBody().getStatus()==200){
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //当前时间
                map.put("createTime",df.format(new Date()));
              
            }
			//将要修改的内容放入map中
            if(StringUtils.isNotEmpty(goodsDescripe)){
                map.put("goodsDescripe",goodsDescripe);
            }
            list.add(map);
          /*  JSONArray jsonArray = JSONObject.parseArray(replies1);*/
            JSONArray jsonArray = JSONArray.parseArray(replies1);
			//将内容进行拼接
            if(list.size()>0){
                jsonArray.add(list.get(0));
            }
            BasicDBObject query = new BasicDBObject();
            BasicDBObject doc = new BasicDBObject();
            query.append("replies",jsonArray);
            doc.put("$set", query);
            //根据id修改语句
            dbCollection.update(query2,doc,false,true);
        }
        return "评论成功";
    }else{
        return "评论失败";
    }
}

 

你可能感兴趣的:(Java,-----,mongodb)