Java MongoDB connectivity Code
package mongoconn;
////import com.mongodb.client.MongoDatabase;
import java.net.UnknownHostException;
import java.sql.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
//import com.mongodb.MongoCredential;
public class myconn{
public static void main( String args[] ) throws UnknownHostException {
// Creating a Mongo client
MongoClient mongo = new MongoClient("localhost" , 27017 );
System.out.println("Connected to the database successfully");
DB db = mongo.getDB("SP");
DBCollection table = db.getCollection("user");
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
document.put("createdDate", new Date(0));
table.insert(document);
}
}
////import com.mongodb.client.MongoDatabase;
import java.net.UnknownHostException;
import java.sql.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
//import com.mongodb.MongoCredential;
public class myconn{
public static void main( String args[] ) throws UnknownHostException {
// Creating a Mongo client
MongoClient mongo = new MongoClient("localhost" , 27017 );
System.out.println("Connected to the database successfully");
DB db = mongo.getDB("SP");
DBCollection table = db.getCollection("user");
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
document.put("createdDate", new Date(0));
table.insert(document);
}
}