需要mongodb的驱动jar(mongo-java-driver-3.2.0.jar)
package mongodb;
import java.net.UnknownHostException;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
public class mongoDB_zsgc {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws UnknownHostException {
try {
/**** 连接数据库 ****/
Mongo mongo = new Mongo("127.0.0.1",27017);
/****获取数据库 ****/
// if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("userMessageDB");
/****获取数据集合 ****/
// if collection doesn't exists, MongoDB will create it for you
DBCollection table = db.getCollection("userList");
/**** 添加数据(10条) ****/
// BasicDBObject document =null;
// for(int i =1;i<=10;i++){
// document = new BasicDBObject();
// document.put("name", "student"+i);
// document.put("age", 18);
// document.put("createdDate", new Date());
// table.insert(document);
// }
/****单条查找数据1****/
// BasicDBObject searchQuery = new BasicDBObject();
// searchQuery.put("name", "student1");
// DBCursor cursor = table.find(searchQuery);
// while (cursor.hasNext()) {
// System.out.println(cursor.next());
// }
/****单条查找数据2 ****/
// BasicDBObject searchQuery3 = new BasicDBObject().append("name", "student1");
// DBCursor cursor3 = table.find(searchQuery3);
// while (cursor3.hasNext()) {
// System.out.println(cursor3.next());
// }
//查询所有的数据库
// for (String db1 : mongo.getDatabaseNames()) {
// System.out.println(db1);
// }
// //查询所有的聚集集合
// for (String name : db.getCollectionNames()) {
// System.out.println(name);
// }
/****修改数据****/
// BasicDBObject query4 = new BasicDBObject();
// query4.put("name", "student10");
//
// BasicDBObject newDocument = new BasicDBObject();
// newDocument.put("name", "kaige");
//
// BasicDBObject updateObj = new BasicDBObject();
// updateObj.put("$set", newDocument);
// table.update(query4, updateObj);
//
//删除数据
deleteColData(table, "student1");
//查询所有数据
DBCursor cursor = table.find();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println(cursor.count());
System.out.println(cursor.getCursorId());
System.out.println(JSON.serialize(cursor));
} catch (MongoException e) {
e.printStackTrace();
}
}
/**
* 数据删除
*/
private static void deleteColData(DBCollection table,String name){
BasicDBObject query = new BasicDBObject();
query.put("name", name);
table.remove(query);
}
}
java操作mongoDB之增删改查
原创
©著作权归作者所有:来自51CTO博客作者betterbertter的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Mybatis之增删改查操作
Mybatis,java,增删改查,互联网,IT
Mybatis java 增删改查 程序员 互联网 -
【Mongodb】 增删改查
查看当前数据库db-----------------------
数据库 插入数据 更新数据