How do I avoid duplicate data in MongoDB (Java)

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 :slight_smile:


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:

  1. Connect to MongoDB: First, establish a connection to your MongoDB instance.
  2. Create a Collection: Get the collection where you want to store the player UUIDs.
  3. Create a Unique Index: Create a unique index on the UUID field to ensure that all UUIDs are unique.
  4. 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:

  1. Connection: The MongoClient connects to the MongoDB instance running on localhost at port 27017.
  2. Database and Collection: The game_data database and players collection are accessed.
  3. Unique Index: The createIndex method with IndexOptions().unique(true) ensures that the UUID field is unique.
  4. 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