我正在尝试使用mongodb在Java中完成此任务。假设我有一份员工名单(名字,姓氏,电话号码)。现在,一些员工可以拥有多个电话号码。
假设我有一份员工列表(我正在解析xml文档):
<contact><firstname>John</firstname><lastname>Smith</lastname><phonenum>555 123 23 23</phonenum></contact>
<contact><firstname>Jane</firstname><lastname>Doe</lastname><phonenum>555 123 44 44</phonenum></contact>
<contact><firstname>John</firstname><lastname>Smith</lastname><phonenum>555 666 66 66 23</phonenum></contact>
mongodb中的结果插入应如下所示:
{ "_id" : ObjectId("5297a3d84a9cb457a3f33b23"), "name" : "John", "lastName" : "Smith", "phone" : [ "555 123 23 23", "555 666 66 66 23" ] }
{ "_id" : ObjectId("5297a3d84a9cb457a3f33b24"), "name" : "Jane", "lastName" : "Doe", "phone" : [ "555 123 44 44" ] }
我尝试的是首先解析文档并插入名字和姓氏。然后,查询firstname和lastname(如果存在),使用$ push更新记录以附加电话号码:
File fXmlFile = new File("contacts.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
Document doc;
try {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("testdb");
dBuilder = dbFactory.newDocumentBuilder();
DBCollection table = db.getCollection("employees");
doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("contact");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
BasicDBObject document = new BasicDBObject();
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String firstName = eElement.getElementsByTagName("name").item(0).getTextContent();
String lastName =eElement.getElementsByTagName("lastName").item(0).getTextContent();
document.put("name", firstName);
document.put("lastName", lastName);
table.insert(document);
String phoneNumber = eElement.getElementsByTagName("phone").item(0).getTextContent();
BasicDBObject query = new BasicDBObject();
query.put("name", firstName);
query.put("lastName", lastName);
BasicDBObject push = new BasicDBObject();
push.put("$push", new BasicDBObject("phone",phoneNumber));
table.update(query, push);
}
}
但我得到以下结果:
{ "_id" : ObjectId("5297a5004a9ca519fad4e94d"), "lastName" : "Smith", "name" : "John", "phone" : [ "555 123 23 23"
, "555 666 66 66 23" ] }
{ "_id" : ObjectId("5297a5004a9ca519fad4e94e"), "lastName" : "Doe", "name" : "Jane", "phone" : [ "555 123 44 44" ]
}
{ "_id" : ObjectId("5297a5004a9ca519fad4e94f"), "name" : "John", "lastName" : "Smith" }
所以基本上,有一个John Smith记录没有添加电话号码,为什么呢?另外为什么我的前两个记录首先显示姓氏?
我对mongodb很新,所以这是非常草率和快速的代码,只是为了看看我如何完成这项任务。
我很乐意感谢任何帮助。
感谢。
答案 0 :(得分:0)
Mongodb具有upsert的概念(如果不存在则插入或如果存在则更新)。
尝试使用:update(DBObject q,DBObject o, boolean upsert, boolean multi)并将upsert标志设置为true。
这样的事情:
collection.update(new BasicDBObject(“name”,“John”)。append(“lastName”,“Smith”),new BasicDBObject(“$ push”,new BasicDBObject(“phone”,“new number”) ),true,false)