大家好,又见面了,我是全栈君。
注意:要增加mongodb对应的jar包
package cn.toto.mongodb;
import java.net.UnknownHostException;
import org.bson.types.ObjectId;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
/**
*使用java代码调用mongodb
*
*@author to–to
*/
publicclass MongoDBDao {
@Test
publicvoid add()throws UnknownHostException {
//建立起连接
Mongo mongo =new Mongo(“192.168.1.100”, 27017);
//依据连接获取到数据库
DB db = mongo.getDB(“test”);
//获取数据库以下的某个集合,针对结合进行操作…
DBCollection dbCollection = db.getCollection(“person”);
//
BasicDBObject dbObject =new BasicDBObject();
dbObject.put(“title”,“奔放洋气有深度,简约时尚国际范“);
dbObject.put(“content”,“高大上“);
// {key:value,keyvalue}
dbCollection.insert(dbObject);
mongo.close();
}
@Test
publicvoid del()throws UnknownHostException {
Mongo mongo =new Mongo(“192.168.1.100”, 27017);
//依据连接获取到数据库
DB db = mongo.getDB(“test”);
//获取数据库以下的某个集合,针对结合进行操作…
DBCollection dbCollection = db.getCollection(“person”);
// {}
DBObject dbObject =new BasicDBObject();
dbCollection.remove(dbObject);
}
/**
*更新
*
*@throws UnknownHostException
*/
@Test
publicvoid update()throws UnknownHostException {
Mongo mongo =new Mongo(“192.168.1.100”, 27017);
//依据连接获取到数据库
DB db = mongo.getDB(“test”);
//获取数据库以下的某个集合。针对结合进行操作…
DBCollection dbCollection = db.getCollection(“person”);
// {}
//设置更新的条件
BasicDBObject query =new BasicDBObject(“_id”,new ObjectId(
“53db556a5bcbcfc947854027”));
//设置更新的内容的对象…
BasicDBObject object = (BasicDBObject) dbCollection.findOne(query);
object.put(“title”,“高端大气上档次“);
dbCollection.update(query, object);
}
@Test
publicvoid find()throws UnknownHostException {
Mongo mongo =new Mongo(“192.168.1.100”, 27017);
//依据连接获取到数据库
DB db = mongo.getDB(“test”);
//获取数据库以下的某个集合。针对结合进行操作…
DBCollection dbCollection = db.getCollection(“person”);
// BasicDBObject dbObject=new BasicDBObject();
// dbObject.put(“content”, “高大上“);
DBCursor cursor = dbCollection.find();
while (cursor.hasNext()) {
DBObject dbObject2 = cursor.next();
System.out.println(dbObject2.toString());
}
// {$lt:{age:20}}
// db.collection.find()
// {}
BasicDBObject basicDBObject =new BasicDBObject();
BasicDBObject basicDBObject2 =new BasicDBObject();
basicDBObject2.put(“age”, 20);
basicDBObject.put(“$lt”, basicDBObject2);
}
}
|
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/116478.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...