Hello guys, I want to store player’s UUIDs into MongoDB. The player’s UUID is a unique string. I am having problems with producing this because of duplicate data.
Hi @Clarence_Kai_Wen_Chung, and welcome to the forums!
Since there wasn’t a reply to your message, I tried to run it by our documentation bot. Here is the response I got
To store unique player UUIDs in MongoDB using the Java Driver, you need to ensure that the UUID
field is unique by creating a unique index on that field. Here is a step-by-step guide to help you achieve this:
- Connect to MongoDB: First, establish a connection to your MongoDB instance.
- Create a Collection: Get the collection where you want to store the player UUIDs.
- Create a Unique Index: Create a unique index on the
UUID
field to ensure that all UUIDs are unique. - Insert Documents: Insert the player UUIDs into the collection.
Here is an example code snippet to illustrate these steps:
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.client.model.IndexOptions;
public class UniqueUUIDExample {
public static void main(String[] args) {
// Connect to MongoDB
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("game_data");
MongoCollection<Document> collection = database.getCollection("players");
// Create a unique index on the UUID field
IndexOptions indexOptions = new IndexOptions().unique(true);
collection.createIndex(new Document("UUID", 1), indexOptions);
// Insert a player UUID
Document player = new Document("UUID", "123e4567-e89b-12d3-a456-426614174000") .append("name", "PlayerOne");
try {
collection.insertOne(player);
System.out.println("Player inserted successfully.");
} catch (Exception e) {
System.out.println("Error inserting player: " + e.getMessage());
}
// Close the connection
mongoClient.close();
}
}
Explanation:
- Connection: The
MongoClient
connects to the MongoDB instance running onlocalhost
at port27017
. - Database and Collection: The
game_data
database andplayers
collection are accessed. - Unique Index: The
createIndex
method withIndexOptions().unique(true)
ensures that theUUID
field is unique. - Insert Document: A player document with a unique
UUID
is inserted. If a duplicate UUID is inserted,
Related Resources
Documents
Docs
Getting Started with MongoDB and Java - CRUD Operations Tutorial
Website