首先,运行数据库:运行 mongo.exe 程序即可启动 MongoDB 交互式命令行环境
1、建立数据库名:
只需要在 MongoDB 命令行环境中运行:
use company
2、查看已存在的数据库
MongoDB 在你插入任何数据之前并不会创建数据库。
你可以使用下面命令来查看系统中已有的数据库,你会发现你刚创建的 company 并不在其中。
show dbs;
3、java连接MongoDB数据库实例:
1 package com.laoxu.test.day02.mongoDBDemo01; 2 3 import java.net.UnknownHostException; 4 5 import com.mongodb.BasicDBObject; 6 import com.mongodb.DB; 7 import com.mongodb.DBCollection; 8 import com.mongodb.DBCursor; 9 import com.mongodb.Mongo; 10 11 /** 12 * mongoDB连接 13 * @author Administrator 14 * 15 */ 16 public class FirstConnectDBTest { 17 private static final String MONGODB_URL = "localhost"; 18 private static final Integer MONGODB_PORT = 27017; 19 private static final String DB_NAME = "company"; 20 21 public static void getConnect(){ 22 try { 23 Mongo mongo = new Mongo(MONGODB_URL,MONGODB_PORT); 24 DB db = mongo.getDB(DB_NAME); 25 DBCollection dbCollection = db.getCollection("employees"); 26 BasicDBObject emplyee = new BasicDBObject(); 27 emplyee.put("name", "aaaaaa"); 28 emplyee.put("no", 2); 29 dbCollection.insert(emplyee); 30 31 BasicDBObject searchObject = new BasicDBObject(); 32 searchObject.put("no", 2); 33 34 DBCursor dbCursor = dbCollection.find(searchObject); 35 while(dbCursor.hasNext()){ 36 System.out.println(dbCursor.next()); 37 } 38 System.out.println("this search query is executed !"); 39 40 } catch (UnknownHostException e) { 41 e.printStackTrace(); 42 } 43 } 44 45 public static void main(String[] args) { 46 getConnect(); 47 } 48 49 }
运行结果:
1 { "_id" : { "$oid" : "5226daa92dce9ea84b7e9e84"} , "name" : "aaaaaa" , "no" : 2} 2 this search query is executed !