好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

mongodb字段值自增长实现代码

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

1.创建计数器集合

 

期望_id字段从1,2,3,4到n,启动一个自动递增的整数序列,如:

?

1

2

3

4

5

6

{

   "_id" :1,

   "title" : "标题" ,

   "content" : "内容1" ,

   "type" : "类型"

}

为此,创建 counters 集合,序列 字段值 可以实现自动长:

?

1

db.createCollection("counters")

初始化集合,以objId作为主键,sequence_value 字段是序列通过自动增长后的一个值:

?

1

db.counters.insert({_id:"objId",sequence_value:0})

2.查询序列号

 

查询返回更新后的序列号

?

1

2

3

4

5

db.counters.findAndModify({

   query: {_id: "objId" },

   update: {$inc:{sequence_value:1}},

   new: true

}).sequence_value;

操作符解释:

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

?

1

2

3

4

5

6

7

8

db.collection.findAndModify({

   query: <document>, //定义关于哪些记录需要修改的选择标准

   sort: <document>, //确定选择标准检索多个文档时应修改的文档

   new: <boolean>, //表示将显示修改后的文档

   fields: <document>, //指定要返回的字段集

   upsert: <boolean> //如果选择标准无法检索文档,则创建一个新文档

   remove: <boolean> //为true,query指定的文档将从数据库中删除

)}

3.测试

 

创建测试集合sms:

?

1

db.createCollection("sms")

在sms集合中新增文档,实现_id 自增长 : 

?

1

2

3

4

5

6

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集合:

?

1

db.sms.find({}).sort({_id:1})

4.java实现

 

java实现以上功能,数据库驱动版本不同运行效果有差异,仅供参考:

?

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

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");

     List<Document> documents = new ArrayList<Document>();

     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");

   FindIterable<Document> findIterable = collection.find();

   MongoCursor<Document> mongoCursor = findIterable.iterator();

   while(mongoCursor.hasNext()){

     System.out.println(mongoCursor.next());

   }

}

5.总结

 

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

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

原文链接:https://blog.csdn.net/zxw08611/article/details/112555628

查看更多关于mongodb字段值自增长实现代码的详细内容...

  阅读:25次