一个简单的入门
例子,演示连接客户端,怎样创建一个数据库、表,怎样实现数据的增、删、改、查等操作
1. 在Eclipse中建立一个Maven工程
2. 获取Mongo Java Driver
class="pom.xml">
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.0</version>
</dependency>
如果不使用Maven工程,可以从https://github.com/mongodb/mongo-java-driver/downloads获取jar包
3. HelloWorld
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
public class MongoDBExample {
public static void main(String[] args) {
try {
// 1. 连接到MongoDB服务器
MongoClient mongo = new MongoClient("localhost", 27017);
// 2. 获取数据库
// 如果指定的数据库[yourdb]不存在,MongoDB将会新建一个数据库
DB db = mongo.getDB("yourdb");
//显示所有数据库
List<String> dbs = mongo.getDatabaseNames();
for(String database: dbs){
System.out.println("db: "+database);
}
// 3. 获取一个表
// 如果表不存在,MongoDB将会新建一个
DBCollection table = db.getCollection("users");
//显示选择的数据库中所有表
Set<String> tables = db.getCollectionNames();
for(String coll : tables){
System.out.println("table: "+coll);
}
// 新增一条记录
BasicDBObject document = new BasicDBObject();
document.put("username", "yourname");
document.put("password", "123456");
document.put("age", 22);
document.put("createdDate", new Date());
table.insert(document);
// 查找并显示一条记录
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("username", "yourname");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
//更新一条记录
BasicDBObject query = new BasicDBObject();
query.put("username", "yourname");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("username", "yourname-update");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
//查找更新后的记录
BasicDBObject searchQuery2 = new BasicDBObject().append("username", "yourname-update");
DBCursor cursor2 = table.find(searchQuery2);
while (cursor2.hasNext()) {
System.out.println(cursor2.next());
}
System.out.println("End");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
4. 运行结果
5. mongo 客户端
6. MongoDB客户端工具RockMongo界面
- 大小: 49 KB
- 大小: 9.3 KB
- 大小: 45.4 KB
- 大小: 42.1 KB
- mongodb.zip (7.7 KB)
- 下载次数: 1