I want to use MongoDB in java, without an IDE or additional tools. I have downloaded mongo-java-driver-3.12.8.jar, and put it in the same folder as my helloMongo.java file.
I then have tried to run it with:
javac -cp "mongo-java-driver.jar" helloMongo.java
java -cp "mongo-java-driver.jar" helloMongo
Only to get that it cannot find the main class.
Then I tried, assuming the main path had been lost in javas braindead implementation:
javac -cp ".;mongo-java-driver.jar" helloMongo.java
java -cp ".;mongo-java-driver.jar" helloMongo
still to no luck. Then I tried:
javac -cp ".;/mongo-java-driver.jar" helloMongo.java
java -cp ".;/mongo-java-driver.jar" helloMongo
And a hundred other variants, and still no luck.
Is an IDE and Gradle essentially required to use Mongo with Java?
package com.javatpoint.java.mongo.db;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class JavaMongoDemo {
public static void main(String[] args){
try{
//---------- Connecting DataBase -------------------------//
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//---------- Creating DataBase ---------------------------//
MongoDatabase db = mongoClient.getDatabase("javatpoint");
//---------- Creating Collection -------------------------//
MongoCollection<Document> table = db.getCollection("employee");
//---------- Creating Document ---------------------------//
Document doc = new Document("name", "Peter John");
doc.append("id",12);
//----------- Inserting Data ------------------------------//
table.insertOne(doc);
}catch(Exception e){
System.out.println(e);
}
}
}
If your package is com.javatpoint.java.mongo.db
, then your class has to be in
./com/javatpoint/java/mongo/db
and assuming you leave the Mongo jar in the same directory as your source, your java
command must be
java -cp ./com/javatpoint/java/mongo/db/mongo-java-driver.jar com.javatpoint.java.mongo.db.helloMongo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.