gpt4 book ai didi

java - MongoDB 的唯一 int _id

转载 作者:行者123 更新时间:2023-12-01 18:24:40 25 4
gpt4 key购买 nike

我正在尝试为 _id 分配唯一的 int。我知道 ObjectID 是一个很好的选择,但在我的例子中我需要使用 int 作为 ID。我正在使用 Random 生成随机 int 并将其分配给新对象。

这是错误:

Exception in thread "main" com.mongodb.MongoWriteException: E11000 duplicate key error 
collection: TOP100SongsUK.artists index: _id_ dup key: { _id: 484624875 }

但是,事实并非如此。目前,我的 Collection 只有一些记录,这是不可能的。什么可能触发此问题?

这是写入数据库的方法,最后一个方法分配一个 ID。

 public boolean add(Artist artist) {
Document artistToInsert = new Document();
artistToInsert.append(ARTIST_ID, assignArtistID()).append(ARTIST_NAME, artist.getName());
boolean validOperation = false;
int attempts = 0;
do {
try {
addArtist(artistToInsert);
validOperation = true;
} catch (DuplicateKeyException e) {
attempts++;
System.out.println("Incorrect ID for Artist");
}
} while (!validOperation || attempts < 3);
if (attempts == 3) {
throw new RuntimeException("Unable to add Artist - Mongo");
}
return true;
}

private boolean addArtist(Document artistToInsert) {
artistCollection.insertOne(artistToInsert);
return true;
}

private static Random intGenerator = new Random();
private int assignArtistID() {
return Math.abs(intGenerator.nextInt());
}

更新:getNextSequence 函数:

static final String ID_PARAM = "idParam";
static final String ID_SEQ = "seq";

static int getNextSequence(MongoCollection<Document> collection){
Document findRequest = new Document();
findRequest.append("_id", ID_PARAM);
Document updateRequest = new Document();
updateRequest.append("$inc", new Document(ID_SEQ,1));
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
options.upsert(true);
options.returnDocument(ReturnDocument.AFTER);
Document returnDoc = collection.findOneAndUpdate(findRequest,updateRequest,options);
return (int) returnDoc.get(ID_SEQ);
}

最佳答案

使用随机 int 来生成 _id mongo 并不是一个好主意。您应该使用 Mongo 使用自动增量序列。

您必须为您的序列创建一个集合,其中包含序列名称和序列编号。然后对于每个插入,获取序列并递增它。

这里有一些链接可以帮助您:

关于java - MongoDB 的唯一 int _id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60245115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com