如何使用java驱动程序在mongodb中的嵌入式文档中推送注释

时间:2016-02-17 16:16:52

标签: arrays mongodb comments push mongo-java-driver

我有以下文件:

enter code here

{ "_id" : ObjectId("56c49b52a5b24ba2a979a964"),

enter code here

}

如何添加新评论{         " comment3":"推送来自java"的评论,         "作者":"爪哇"         }在帖子ID下的评论部分:java中的1

1 个答案:

答案 0 :(得分:1)

你需要匹配postId 1,然后将新评论推送到“评论”,如下所示:

String idimlookingfor = "074804007527";

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();

String xpathexpression = String.format("//TransactionLine/ItemLine/ItemCode[POSCode=%s]/../..", idimlookingfor);
XPathExpression expr = xpath.compile(xpathexpression);

Object result = expr.evaluate(document, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
使用java驱动程序编写它很容易,“更新”部分就是这样的:

db.[your collection name].update({"RoomPost" :{$elemMatch :{"postId" : 1}}}, {$push : {"RoomPost.$.comments": {"comment3" :"some comment"}}})

希望它有所帮助。