Lesson 7. Creating users database with MongoDB
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.json.JSONObject;11:01:15.406 [pool-1-thread-1] DEBUG org.mongodb.driver.protocol.query - Query completed
11:01:25.174 [cluster-ClusterId{value='554dbecb1b554f11e86c3a69', description='null'}-localhost:27017] DEBUG org.mongodb.driver.cluster - Checking status of localhost:27017private String check(String first_name, String last_name, int user_id, String username) {
MongoClientURI connectionString = new MongoClientURI("mongodb://host:port");
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase("db_name");
MongoCollection<Document> collection = database.getCollection("users");
long found = collection.count(Document.parse("{id : " + Integer.toString(user_id) + "}"));
if (found == 0) {
Document doc = new Document("first_name", first_name)
.append("last_name", last_name)
.append("id", user_id)
.append("username", username);
collection.insertOne(doc);
mongoClient.close();
System.out.println("User not exists in database. Written.");
return "no_exists";
} else {
System.out.println("User exists in database.");
mongoClient.close();
return "exists";
}
}Last updated