1、查询mongodb单个字段的所有值内容:db.getCollection('amac').find({},{"managerName":1,"_id":0}) //PS:"_id":0表示不显示id值
java:
//mongoDB数据读取,存入MYSQL数据库
private static void readMongo(){
Connection conn = MysqlUtil.getConnection();//连接mysql
Statement statement = null;
MongoClient mongoClient=new MongoClient("119.xx.xx.xxx",27017);//连接mongoDB数据库
DB database=mongoClient.getDB("row");//获取数据库
DBCollection collection = database.getCollection("amac");//集合名
DBCursor cursor = collection.find();
System.out.println("从数据集中读取数据:");
while(cursor.hasNext()){
BasicDBObject bdbObj = (BasicDBObject) cursor.next();
if(bdbObj != null){
String managerName=bdbObj.getString("managerName");//读取mongoDB数据库row的amac集合的指定字段managerName
try{
statement =conn.createStatement();
String sql="insert into manager(managerName) values('"+managerName+"')";//存入mysql数据库的机构列表
statement.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(null!=statement)
{
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
System.out.println("over.");
}
其中getConnection()函数如下
//连接数据库
private static Connection connection=null;private static String username="user";private static String password="password";private static String DB_URL="jdbc:mysql://localhost:3306/mingzi?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";private static String DB_DRIVER="com.mysql.jdbc.Driver";public static Connection getConnection() { try { Class. forName( DB_DRIVER); connection=DriverManager. getConnection( DB_URL, username, password); System. out.println( "连接数据库成功:"+ connection); } catch (Exception e) { System. out.println( "数据库连接异常..."); e.printStackTrace(); } return connection;}