import java.net.UnknownHostException;
import java.util.ArrayList;
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.DBObject;
import com.mongodb.Mongo;
public class MongoTest {
private static String dbIp = "localhost";
private static int dbPort = 27017;
private static String dbUser = "user1";
public static void main(String[] args) {
MongoTest mongo = new MongoTest();
DBCollection collection;
try {
//获取连接
collection = mongo.getCollection();
//插入数据
mongo.insertDate(collection);
//查询数据
mongo.queryDate(collection);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public DBCollection getCollection () throws UnknownHostException{
//实例化Mongo对象,
Mongo mongo = new Mongo(dbIp, dbPort);
//连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立
DB db = mongo.getDB(dbUser);
//从Mongodb中获得名为myData的数据集合,如果该数据集合不存在,Mongodb会为其新建立
DBCollection collection = db.getCollection("myData");
return collection;
}
public void insertDate(DBCollection collection){
// 创建要保存的document
BasicDBObject document = new BasicDBObject();
List<DBObject> documents = new ArrayList<DBObject>();
document.put("id", 1113);
document.put("msg", "mongodb test1 花生酱");
document.put("msg2", "mongodb test1 花生酱");
document.put("msg3", "mongodb test1 花生酱");
documents.add(document);
document = new BasicDBObject();
document.put("id", 1114);
document.put("msg4", "mongodb test2 暗世界");
document.put("msg5", "mongodb test2 暗世界");
documents.add(document);
//将新建立的document保存到collection中去
collection.insert(document); //单条插入
collection.insert(documents); //多条集合插入
}
public void queryDate(DBCollection collection){
// 创建要查询的document
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("id", 1113);
// 使用collection的find方法查找document
DBCursor cursor = collection.find(searchQuery);
//循环输出结果
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
searchQuery.put("id", 1114);
cursor = collection.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
}
Java 连接 操作Mongodb 添加查询
最新推荐文章于 2024-09-02 14:21:53 发布