加数据到BasicDBObject)
public void testSave3(){
DBCollection table = db.getCollection("person");
Map maps = new HashMap();
maps.put("name", "小李");
maps.put("password", "xiaozhang");
maps.put("age", 24);
BasicDBObject document = new BasicDBObject(maps);//这样添加后,对象里的字段是无序的。
table.insert(document);
}
在mongodb shell中使用命令查看数据
> db.person.find()
{ "_id" : ObjectId("537761da2c82bf816b34e6cf"), "name" : "jack", "age" : 50 }
{ "_id" : ObjectId("53777096d67d552056ab8916"), "name" : "小王", "age" : 24 }
{ "_id" : ObjectId("5377712cd67d84f62c65c4f6"), "name" : "小郭", "age" : 24 }
{ "_id" : ObjectId("53777230d67dfe576de5079a"), "name" : "小张", "password" : "xiaozhang", "age" : "23" }
{ "_id" : ObjectId("537772e9d67df098a26d79a6"), "age" : 24, "name" : "小李", "password" : "xiaozhang" }
9、更新对象
我们可以结合【mongodb shell命令】db.person.update({name:"小李"},{$set:{password:"hello"}})来理解Java是如何操作对象来更新的。{name:"小李"}是一个BasicDBObject,{$set:{password:"hello"}也是一个BasicDBObject,这样理解的话,你就会觉得mongodb shell命令操作和Java操作很相似。
public void testUpdate() {
DBCollection table = db.getCollection("person");
BasicDBObject query = new BasicDBObject();
query.put("name", "小张");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("age", 23);
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
}
// 命令操作:db.person.update({name:"小李"},{$set:{password:"hello"}})
public void testUpdate2() {
DBCollection table = db.getCollection("person");
BasicDBObject query = new BasicDBObject("name", "小张");
BasicDBObject newDocument = new BasicDBObject("age", 24);
BasicDBObject updateObj = new BasicDBObject("$set", newDocument);
table.update(query, updateObj);
}
10、删除对象
可参考db.users.remove({name:"小李"})命令来理解Java操作对象
public void testDelete(){
DBCollection table = db.getCollection("person");
BasicDBObject query = new BasicDBObject("name", "小李");
table.remove(query);
}
11、参考
Java + MongoDB Hello World Example(推荐)
12、你可能感兴趣
【MongoDB数据库】如何安装、配置MongoDB
【MongoDB数据库】MongoDB 命令入门初探