欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mongodb初探-小试牛刀

程序员文章站 2022-03-12 09:44:50
...
1、启动数据库服务
2、下载mongodb的Java驱动,并构建到java工程中,下载地址:https://github.com/mongodb/mongo-java-driver/downloads
3、编写如下代码

package com.ljq.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
/**
* Mongodb connect & insert & query simple example
* @author [email protected]
*/
public class DbTest {
public static void main(String[] args) throws Exception{
/*
The Mongo object instance actually represents a pool of connections to the database;
you will only need one object of class Mongo even with multiple threads.
*/
// Mongo mongo = new Mongo();
Mongo mongo = new Mongo("127.0.0.1");

List<String> list = mongo.getDatabaseNames();
// 打印数据库名字
int index = 0;
for (String db : list) {
System.out.println("数据库"+(++index)+":"+db);
}
System.out.println("=============================");

DB db = mongo.getDB( "mydb1" );
Set<String> colls = db.getCollectionNames();
// 打印mydb1中的链接
index = 0;
for (String s : colls) {
System.out.println("连接"+(++index)+":"+s);
}
System.out.println("=============================");

// 获取某个链接
DBCollection collection = db.getCollection("mydb1");

Map<String, Object> data = new HashMap<String, Object>();
data.put("_id", UUID.randomUUID());
data.put("name", "lijiaqian2011");
data.put("email", "[email protected]");
data.put("address", "BeiJing China");
data.put("company", "BeiJing Boeh Technology");
data.put("salary", 6000f);
data.put("addtime", new Date());

BasicDBObject doc = new BasicDBObject();
doc.putAll(data);

// 插入数据
collection.insert(doc);

BasicDBObject query = new BasicDBObject();
query.put("name", "lijiaqian2011");

// 查询数据
DBObject mydoc = collection.findOne(query);

System.out.println("email:"+mydoc.get("email"));
}
}


4、执行结果如下图:


[img]http://dl.iteye.com/upload/attachment/583279/3fd5f2bb-792f-3232-9774-4e9a72291264.jpg[/img]
相关标签: mongodb java