1.连接mongo数据库
Mongo mongo = new Mongo("localhost",27017); DB db =mongo.getDB("test"); DBCollection collections = db.getCollection("customer");
2.查询集合所有文档
DBCursor dbCursor = collections.find(); while (dbCursor.hasNext()) { System.out.println(dbCursor.next().get("name")); } mongo.close();
3.删除集合中文档
//根据Id进行删除(id为特殊类型) BasicDBObject o = new BasicDBObject("_id" ,new ObjectId("321321fdf21312")); //根据其他字段删除 BasicDBObject o = new BasicDBObject("name" ,"zhangsan"); collections.remove(o); mongo.close();
4.向集合插入文档
BasicDBObject c = new BasicDBObject(); c.put("name", "zhangsan"); c.put("age", "24"); collections.insert(c); mongo.close();
5.更新集合中的文档
BasicDBObject query = new BasicDBObject("_id" ,new ObjectId("321321fdf21312")); BasicDBObject object = (BasicDBObject)collections.findOne(query); object.put("name","wangwu"); collections.update(query, object); mongo.close();
时间: 2024-10-31 22:23:43