加入收藏 | 设为首页 | 会员中心 | 我要投稿 驾考网 (https://www.jiakaowang.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 系统 > 正文

请看MongoDB的属性值自增案例

发布时间:2023-10-05 13:37:30 所属栏目:系统 来源:
导读: MongoDB是一个基于分布式文件存储的数据库,是由C++语言编写的,目的在于为web应用听可扩展的高性能数据存储解决方案。MongoDB与SQL还是存在很大不同的,例如它没有像 SQL 一样有自动增长的功能,那么mongodb字段

    MongoDB是一个基于分布式文件存储的数据库,是由C++语言编写的,目的在于为web应用听可扩展的高性能数据存储解决方案。MongoDB与SQL还是存在很大不同的,例如它没有像 SQL 一样有自动增长的功能,那么mongodb字段值自增长要如何实现呢?

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

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.总结

    以上就是关于是实现mongodb字段值自增长的介绍,有了字段自增长功能,那么在新增数据时,就不需要再手动插入值了,这样也可以更好的实现订单流水号、编码的流水号等功能。

(编辑:驾考网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章