Fix one error of Java The line 16 has errors, which is shown in picture package
ID: 3737402 • Letter: F
Question
Fix one error of Java
The line 16 has errors, which is shown in picture
package db.mongodb;
import java.text.ParseException;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.IndexOptions;
// Create tables for MongoDB (all pipelines).
public class MongoDBTableCreation {
// Run as Java application to create MongoDB tables with index.
public static void main(String[] args) throws ParseException {
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase(MongoDBUtil.DB_NAME);
// Step 1: remove old tables.
db.getCollection("users").drop();
db.getCollection("items").drop();
// Step 2: create new tables, populate data and create index.
db.getCollection("users")
.insertOne(new Document().append("first_name", "John").append("last_name", "Smith")
.append("password", "3229c1097c00d497a0fd282d586be050").append("user_id", "1111"));
// make sure user_id is unique.
IndexOptions indexOptions = new IndexOptions().unique(true);
// use 1 for ascending index , -1 for descending index
// Different to MySQL, users table in MongoDB also has history info.
db.getCollection("users").createIndex(new Document("user_id", 1), indexOptions);
// make sure item_id is unique.
// Different to MySQL, items table in MongoDB also has categories info.
db.getCollection("items").createIndex(new Document("item_id", 1), indexOptions);
mongoClient.close();
System.out.println("Import is done successfully.");
}
}
Explanation / Answer
Hi,
You can use the below way to get DB connection in MongoDatabase.
you can declare your database name and use it.
private final static String databaseName = "testing";
MongoDatabase db = mongoClient.getDatabase(databaseName);
(or)
If the DB name and the database details are already in the properties file. You can use below way directly.
Sample to retrieve DB connection:
private MongoConnectionUtils mongo = null;
private MongoClient client = null;
public DeleteDocsImpl() {
mongo = new MongoConnectionUtils();
client = mongo.getMongoConnection();
}
@Override
public void loadAllMethods() {
deleteDocument();
}
public void deleteDocument() {
MongoDatabase databaseName = null;
MongoCollection collection = null;
Bson query = null;
try {
databaseName = client.getDatabase(mongo.getDataBase());
collection = databaseName.getCollection(mongo.getSampleCollection());
query = eq("name1", "tester");
DeleteResult result = collection.deleteMany(query);
if (result.wasAcknowledged()) {
log.info("Document deleted : " + result.getDeletedCount());
}
} catch (MongoException e) {
log.error("Exception occurred : " + e, e);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.