Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
MongoDBConnector.java 1.59 KiB
package database;

import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

import java.util.Arrays;
//THIS IS A CONNECTION TEST
public class MongoDBConnector {

    public static void main(String[] args) {
        // Replace credentials and dbname with actual values
        final String uri = "mongodb+srv://Cluster03790:dlVzT2Z2bEh9@cluster03790.tk4cwyy.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";

        try (MongoClient mongoClient = MongoClients.create(uri)) {
            // Connect to the MongoDB cluster and access a database
            MongoDatabase database = mongoClient.getDatabase("myFirstDatabase");

            // Access a collection
            MongoCollection<Document> collection = database.getCollection("testCollection");

            // Create a document to insert
            Document doc = new Document("name", "MongoDB")
                    .append("type", "database")
                    .append("count", 1)
                    .append("versions", Arrays.asList("v3.2", "v4.0", "v4.2"))
                    .append("info", new Document("x", 203).append("y", 102));

            // Insert the document into the collection
            collection.insertOne(doc);

            // Retrieve and print the first document from the collection
            Document myDoc = collection.find().first();
            System.out.println(myDoc.toJson());
        } catch (Exception e) {
            System.err.println("An error occurred: " + e);
        }
    }
}