首先,我们在windows下安装mongodb数据库。
代码如下:
package io.mogo; import java.util.Map; import org.apache.commons.lang3.StringUtils; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.WriteResult; /** * Hello world! * */ public class App { private static final String host = "localhost"; private static final int port = 27017; private static final String userName = ""; private static final String password = ""; private static final String dataBaseName = "test"; private static DB db; public static void main( String[] args ) throws Exception { System.out.println( "Hello World!" ); connMongoDB(); find("person", "name", "xiaoming"); DBObject newObj = new BasicDBObject(); newObj.put("name", "xiaoming"); newObj.put("desc", "i am xiaoming"); update("person", "name", "xiaoming", newObj); find("person", "name", "xiaoming"); } public static void connMongoDB() throws Exception { Mongo mongo = new Mongo(host, port); db = mongo.getDB(dataBaseName); if (!StringUtils.isEmpty(userName) || !StringUtils.isEmpty(password)) { db.authenticate(userName, password.toCharArray()); } } public static void find(String tableName, String key, String value){ DBObject obj = new BasicDBObject(); obj.put(key, value); DBCollection dbCollection = db.getCollection(tableName); DBCursor dbCursor = dbCollection.find(obj); while(dbCursor.hasNext()){ Map map = (Map)dbCursor.next(); System.out.println(map); } } public static boolean delete(String tableName, String key, String value){ DBObject obj = new BasicDBObject(); obj.put(key, value); DBCollection dbCollection = db.getCollection(tableName); WriteResult result = dbCollection.remove(obj); if(result.getN() > 0){ System.out.println("删除数据成功!"); return true; }else{ return false; } } public static boolean insert(String tableName, DBObject obj){ DBCollection dbCollection = db.getCollection(tableName); long num = dbCollection.count(); dbCollection.insert(obj); if(dbCollection.count() - num > 0){ System.out.println("插入数据成功!"); return true; }else{ return false; } } public static boolean update(String tableName, String key, String value, DBObject newValue){ DBObject obj = new BasicDBObject(); obj.put(key, value); DBCollection dbCollection = db.getCollection(tableName); DBObject oldValue = dbCollection.findOne(obj); WriteResult result = dbCollection.update(oldValue, newValue); if(result.getN() > 0){ System.out.println("数据更新成功!"); return true; }else return false; } }
忍者必须死34399账号登录版 最新版v1.0.138v2.0.72
下载勇者秘境oppo版 安卓版v1.0.5
下载忍者必须死3一加版 最新版v1.0.138v2.0.72
下载绝世仙王官方正版 最新安卓版v1.0.49
下载Goat Simulator 3手机版 安卓版v1.0.8.2
Goat Simulator 3手机版是一个非常有趣的模拟游
Goat Simulator 3国际服 安卓版v1.0.8.2
Goat Simulator 3国际版是一个非常有趣的山羊模
烟花燃放模拟器中文版 2025最新版v1.0
烟花燃放模拟器是款仿真的烟花绽放模拟器类型单机小游戏,全方位
我的世界动漫世界 手机版v友y整合
我的世界动漫世界模组整合包是一款加入了动漫元素的素材整合包,
我的世界贝爷生存整合包 最新版v隔壁老王
我的世界MITE贝爷生存整合包是一款根据原版MC制作的魔改整