• 企业400电话
  • 网络优化推广
  • AI电话机器人
  • 呼叫中心
  • 全 部 栏 目

    网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    mongodb字段值自增长实现代码
    POST TIME:2021-10-18 23:11

    MongoDB 没有像 SQL 一样有自动增长的功能, MongoDB 的 _id 是系统自动生成的12字节唯一标识。但在某些情况下,我们可能需要实现 ObjectId 自动增长功能。由于 MongoDB 没有实现这个功能,我们可以通过编程的方式来实现,以下我们将在 counters 集合中实现_id字段自动增长。

    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;

    操作符解释:

    $inc可以对文档的某个值为数字型(只能为满足要求的数字)的键进行增减的操作;

    db.collection.findAndModify({
      query: document>, //定义关于哪些记录需要修改的选择标准
      sort: document>, //确定选择标准检索多个文档时应修改的文档
      new: boolean>, //表示将显示修改后的文档
      fields: document>, //指定要返回的字段集
      upsert: boolean> //如果选择标准无法检索文档,则创建一个新文档
      remove: boolean> //为true,query指定的文档将从数据库中删除
    )}

    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 addSms(){
      int id = getNextSequenceValue();
      if(id != 0){
        DBCollection collection = conn.getCollection("sms");
        ListDocument> documents = new ArrayListDocument>();
        for(int i = 0; i  20; i++){
          int id = getNextSequenceValue();
          Document document = new Document("_id", id).
          append("title", "标题" + i).
          append("content", "短信" + i). 
          append("type", 1);
          documents.add(document);
        }
        collection.insertMany(documents); 
        System.out.println("文档插入成功"); 
     
      }
    }
     
    /**
     * 查询集合
     */
    public static void findSms(){
      DBCollection collection = conn.getCollection("sms");
      FindIterableDocument> findIterable = collection.find(); 
      MongoCursorDocument> mongoCursor = findIterable.iterator(); 
      while(mongoCursor.hasNext()){ 
        System.out.println(mongoCursor.next()); 
      }
    }

    5.总结

    有了字段自增长功能,可以实现订单流水号、编码的流水号等功能,可以实现同MySQL自增字段、Oracle序列的相同效果。

    到此这篇关于mongodb字段值自增长实现的文章就介绍到这了,更多相关mongodb字段值自增长内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    您可能感兴趣的文章:
    • MongoDB进阶之动态字段设计详解
    • pymongo实现控制mongodb中数字字段做加法的方法
    • MongoDB查询字段没有创建索引导致的连接超时异常解案例分享
    • MongoDB查询操作限制返回字段的方法
    上一篇:mongoDB使用投影剔除‘额外’字段的操作过程
    下一篇:mongos崩溃后无法重启问题的解决方法
  • 相关文章
  • 

    关于我们 | 付款方式 | 荣誉资质 | 业务提交 | 代理合作


    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

    X

    截屏,微信识别二维码

    微信号:veteran88

    (点击微信号复制,添加好友)

     打开微信