java对mongoDB的基本操作 ,游标使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | <br>package com.mongodb.text; import java.net.UnknownHostException; import java.util.List; import org.bson.types.ObjectId; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoException; public class MongoDb { //1.建立一个Mongo的数据库连接对象 static Mongo connection = null ; //2.创建相关数据库的连接 static DB db = null ; public MongoDb(String dbName) throws UnknownHostException, MongoException{ connection = new Mongo( "127.0.0.1:27017" ); db = connection.getDB(dbName); } public static void main(String[] args) throws UnknownHostException, MongoException { //实例化 MongoDb mongoDb = new MongoDb( "foobar" ); /** * 1.创建一个名字叫javadb的数据库 */ // mongoDb.createCollection("javadb"); /** * 2.为集合javadb添加一条数据 */ // DBObject dbs = new BasicDBObject(); // dbs.put("name", "uspcat.com"); // dbs.put("age", 2); // List<String> books = new ArrayList<String>(); // books.add("EXTJS"); // books.add("MONGODB"); // dbs.put("books", books); // mongoDb.insert(dbs, "javadb"); /** * 3.批量插入数据 */ // List<DBObject> dbObjects = new ArrayList<DBObject>(); // DBObject jim = new BasicDBObject("name","jim"); // DBObject lisi = new BasicDBObject("name","lisi"); // dbObjects.add(jim); // dbObjects.add(lisi); // mongoDb.insertBatch(dbObjects, "javadb"); /** * 4.根据ID删除数据 */ // mongoDb.deleteById("502870dab9c368bf5b151a04", "javadb"); /** * 5.根据条件删除数据 */ // DBObject lisi = new BasicDBObject(); // lisi.put("name", "lisi"); // int count = mongoDb.deleteByDbs(lisi, "javadb"); // System.out.println("删除数据的条数是: "+count); /** * 6.更新操作,为集合增加email属性 */ // DBObject update = new BasicDBObject(); // update.put("$set", // new BasicDBObject("eamil","uspcat@126.com")); // mongoDb.update(new BasicDBObject(), // update,false,true,"javadb"); /** * 7.查询出persons集合中的name和age */ // DBObject keys = new BasicDBObject(); // keys.put("_id", false); // keys.put("name", true); // keys.put("age", true); // DBCursor cursor = mongoDb.find(null, keys, "persons"); // while (cursor.hasNext()) { // DBObject object = cursor.next(); // System.out.println(object.get("name")); // } /** * 7.查询出年龄大于26岁并且英语成绩小于80分 */ // DBObject ref = new BasicDBObject(); // ref.put("age", new BasicDBObject("$gte",26)); // ref.put("e", new BasicDBObject("$lte",80)); // DBCursor cursor = mongoDb.find(ref, null, "persons"); // while (cursor.hasNext()) { // DBObject object = cursor.next(); // System.out.print(object.get("name")+"-->"); // System.out.print(object.get("age")+"-->"); // System.out.println(object.get("e")); // } /** * 8.分页例子 */ DBCursor cursor = mongoDb.find( null , null , 0, 3, "persons" ); while (cursor.hasNext()) { DBObject object = cursor.next(); System. out .print( object . get ( "name" )+ "-->" ); System. out .print( object . get ( "age" )+ "-->" ); System. out .println( object . get ( "e" )); } //关闭连接对象 connection.close(); } /** * 穿件一个数据库集合 * @param collName 集合名称 * @param db 数据库实例 */ public void createCollection(String collName){ DBObject dbs = new BasicDBObject(); db.createCollection( "javadb" , dbs); } /** * 为相应的集合添加数据 * @param dbs * @param collName */ public void insert(DBObject dbs,String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); //2.插入操作 coll.insert(dbs); } /** * 为集合批量插入数据 * @param dbses * @param collName */ public void insertBatch(List<DBObject> dbses,String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); //2.插入操作 coll.insert(dbses); } /** * 根据id删除数据 * @param id * @param collName * @return 返回影响的数据条数 */ public int deleteById(String id,String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); DBObject dbs = new BasicDBObject( "_id" , new ObjectId(id)); int count = coll.remove(dbs).getN(); return count; } /** * 根据条件删除数据 * @param id * @param collName * @return 返回影响的数据条数 */ public int deleteByDbs(DBObject dbs,String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); int count = coll.remove(dbs).getN(); return count; } /** * 更新数据 * @param find 查询器 * @param update 更新器 * @param upsert 更新或插入 * @param multi 是否批量更新 * @param collName 集合名称 * @return 返回影响的数据条数 */ public int update(DBObject find, DBObject update, boolean upsert, boolean multi, String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); int count = coll.update(find, update, upsert, multi).getN(); return count; } /** * 查询器(分页) * @param ref * @param keys * @param start * @param limit * @return */ public DBCursor find(DBObject ref , DBObject keys, int start, int limit, String collName){ DBCursor cur = find( ref , keys, collName); return cur.limit(limit).skip(start); } /** * 查询器(不分页) * @param ref * @param keys * @param start * @param limit * @param collName * @return */ public DBCursor find(DBObject ref , DBObject keys, String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); DBCursor cur = coll.find( ref , keys); return cur; } } |
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.2.2</version> </dependency>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import java.util.ArrayList; import org.bson.Document; import java.util.List; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.FindIterable; public class MongodbAppHbaseTest { public static void main(String[] args){ try { //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址 //ServerAddress()两个参数分别为 服务器地址 和 端口 ServerAddress serverAddress = new ServerAddress( "1.1.1.1" ,27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码 MongoCredential credential = MongoCredential.createScramSha1Credential( "xxx" , "xxx" , "xxx" .toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //通过连接认证获取MongoDB连接 MongoClient mongoClient = new MongoClient(addrs, credentials); //连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase( "name" ); System. out .println( "Connect to database successfully" ); // mongoDatabase.createCollection("xxx"); // System.out.println("集合创建成功"); MongoCollection<Document> collection = mongoDatabase.getCollection( "xxx" ); System. out .println( "集合 xxx选择成功" ); //检索所有文档 /** * 1. 获取迭代器FindIterable<Document> * 2. 获取游标MongoCursor<Document> * 3. 通过游标遍历检索出的文档集合 * */ FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); int i=0; while (mongoCursor.hasNext()){ System. out .println(mongoCursor.next()); i++; } System. out .println( "i=" +i); } catch (Exception e) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | 上篇博客介绍了java操作mongoDB进行对文件的处理。现在来介绍一下对文档的处理。和对文件的处理一样,也是通过java驱动中提供的几个类相互作用完成的。这几个类分别是: DBCollection类:指定数据库中指定集合的实例,提供了增删改查等一系列操作。在关系型数据库中,对数据的增删改查操作是建立在表的基础上的,在mongodb中是建立在集合的基础上进行的。 DBObject接口:DBObject是键值的映射,因此,可以将DBObject的实现类作为查询的返回结果,也可以作为查询条件 DBCursor:游标,返回结果的集合。 下面是部分实例: Mongo mongo = new Mongo(); DB db = mongo.getDB( "myMongoDB" ); DBCollection course = db.getCollection( "course" ); //对myMongoDB数据库中course集合进行操作 //添加操作 //下面分别是创建文档的几种方式:1. .append() 2. .put() 3. 通过map 4. 将json转换成DBObject对象 DBObject english = new BasicDBObject().append( "name" , "english" ).append( "score" , 5).append( "id" ,1); course.insert(english); DBObject math = new BasicDBObject(); math.put( "id" , 2); math.put( "name" , "math" ); math.put( "score" , 10); course.insert(math); Map<String,Object> map = new HashMap<String,Object>(); map.put( "name" , "physics" ); map.put( "score" , 10); map.put( "id" , 3); DBObject physics= new BasicDBObject(map); course.insert(physics); String json = "{'name':'chemistry','score':10,'id':4}" ; DBObject chemistry =(DBObject)JSON.parse(json); course.insert(chemistry); List<DBObject> courseList = new ArrayList<DBObject>(); DBObject chinese = new BasicDBObject().append( "name" , "chinese" ).append( "score" , 10).append( "id" , 5); DBObject history = new BasicDBObject().append( "name" , "history" ).append( "score" , 10).append( "id" , 6); courseList.add(chinese); courseList.add(history); course.insert(courseList); //添加内嵌文档 String json2 = " {'name':'english','score':10,'teacher':[{'name':'柳松','id':'1'},{'name':'柳松松','id':2}]}" ; DBObject english2= (DBObject)JSON.parse(json); course.insert(english2); List<DBObject> list = new ArrayList<DBObject>(); list.add( new BasicDBObject( "name" , "柳松" ).append( "id" ,1)); list.add( new BasicDBObject( "name" , "柳松松" ).append( "id" ,2)); DBObject english3= new BasicDBObject().append( "name" , "english" ).append( "score" ,10).append( "teacher" ,list); //查询 //查询所有、查询一个文档、条件查询 DBCursor cur = course.find(); while (cur.hasNext()){ DBObject document = cur.next(); System. out .println(document. get ( "name" )); } DBObject document = course.findOne(); String name=(String)document. get ( "name" ); System. out .println(name); //查询学分=5的 DBObject query1 = new BasicDBObject( "score" ,5); DBObject query2 = new BasicDBObject( "score" , new BasicDBObject( "$gte" ,5)); DBCursor cur2 = course.find(query2); //条件表达式:$ge(>) $get(>=) $lt(<) $lte(<=) $ne(<>) $in $nin $all $exists $or $nor $where $type等等 //查找并修改 DBObject newDocument = course.findAndModify( new BasicDBObject( "score" ,5), new BasicDBObject( "score" ,15)); //更新操作 //q:更新条件 o:更新后的对象 course.update( new BasicDBObject( "score" ,10), new BasicDBObject( "test" ,15)); course.update( new BasicDBObject( "score" ,15), new BasicDBObject( "$set" , new BasicDBObject( "isRequired" , true ))); //两个的区别是,第一个更新是将{"test":15}这个文档替换原来的文档, //第二个更新添加了条件表达式$set,是在原来文档的基础上添加"isRequired"这个键 //条件表达式:$set $unset $push $inc $push $push $addToSet $pull $pullAll $pop等等 //当_id相同时,执行save方法相当于更新操作 course.save( new BasicDBObject( "name" , "math" ).append( "_id" , 1)); course.save( new BasicDBObject( "name" , "数学" ).append( "_id" , 1)); //删除符合条件的文档 course.remove( new BasicDBObject( "score" ,15)); //删除集合及所有文档 course.drop(); 上面只是介绍了一些简单的操作,具体复杂的查询更新可以根据需求再去查找文档资料。其实,不管操作简单还是复杂,其核心都是对DBObject和DBCollection的操作,主要掌握DBObject如何构造键值对,以及一些条件表达式。 |
分类:
mgo
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人