mongodb完成字段值自动增长功能示例
发布时间:2022-03-05 09:35:03 所属栏目:系统 来源:互联网
导读:MongoDB是一个基于分布式文件存储的数据库,是由C++语言编写的,目的在于为web应用听可扩展的高性能数据存储解决方案。MongoDB与SQL还是存在很大不同的,例如它没有像 SQL 一样有自动增长的功能,那么mongodb字段值自增长要如何实现呢? 1.创建计数器集合 期
MongoDB是一个基于分布式文件存储的数据库,是由C++语言编写的,目的在于为web应用听可扩展的高性能数据存储解决方案。MongoDB与SQL还是存在很大不同的,例如它没有像 SQL 一样有自动增长的功能,那么mongodb字段值自增长要如何实现呢? 1.创建计数器集合 期望_id字段从1,2,3,4到n,启动一个自动递增的整数序列,如: { "_id":1, "title": "标题", "content": "内容1", "type": "类型" } 为此,创建 counters 集合,序列字段值可以实现自动长: db.createCollection("counters") 初始化集合,以objId作为主键,sequence_value 字段是序列通过自动增长后的一个值: db.counters.insert({_id:"objId",sequence_value:0}) 2.查询序列号 查询返回更新后的序列号 db.counters.findAndModify({ query: {_id: "objId" }, update: {$inc:{sequence_value:1}}, new: true }).sequence_value; 3.测试 创建测试集合sms: db.createCollection("sms") 在sms集合中新增文档,实现_id自增长: db.sms.insert({ _id: db.counters.findAndModify({query:{_id: "objId" },update: {$inc:{sequence_value:1}},"new":true}).sequence_value, title: "标题1", content: "短信1", type: "1" }) 查询sms集合: db.sms.find({}).sort({_id:1}) 4.java实现 java实现以上功能,数据库驱动版本不同运行效果有差异,仅供参考: private MongoDatabase conn; static{ this.conn = getDatabase(databaseName); } /** * 连接数据库 * @param databaseName 数据库名称 * @return 数据库连接对象 */ private static MongoDatabase getDatabase(databaseName){ MongoDatabase mongoDatabase = null; try{ // 连接到 mongodb 服务 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName); System.out.println("Connect to database successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } return mongoDatabase; } /** * 获取最新序列号 * @return 序列号 */ private static int getNextSequenceValue(){ DBCollection collection = conn.getCollection("counters"); DBObject query = new BasicDBObject("_id", new BasicDBObject("$eq", "objId")); DBObject newDocument =new BasicDBObject(); newDocument.put("$inc", new BasicDBObject().append("sequence_value", 1)); newDocument.put("new": true); DBObject ret = collection.findAndModify(query, newDocument); if (ret == null){ return 0; }else{ return (Integer)ret.get("sequence_value"); } } /** * 查询集合 */ public static void findSms(){ DBCollection collection = conn.getCollection("sms"); FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ System.out.println(mongoCursor.next()); } (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |