In: Computer Science
Develop a function to read a document in the MongoDB database
“city” in the collection “inspections.” Be sure it can handle error
conditions gracefully.
a. Input -> arguments to function should be the key/value lookup
pair to use with the MongoDB driver find API call
b. return -> result in JSON format if successful else MongoDB
returned error message
1) Here I am using Java to create a method which would get retire data from mongo db based on key/value argument
// getDataFromMongoDB is a method that would take two arguments of string type
public JSONObject getDataFromMongoDB(string key,string value){
// Initialize name of mongo database
String mongoDB="city";
//initialize name of mongo db collection
string mongoCollection="inspections";
// Connection string to mongo db that takes a end point to mongo db
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
//create object of mongoclient class
MongoClient mongoClient = new MongoClient(connectionString);
// Get object of mongo database
MongoDatabase database = mongoClient.getDatabase(mongoDB);
//Get the mongo collection object
MongoCollection<Document> collection = database.getCollection(mongoCollection);
// Find the first document in which key-value pair is matched
Document myDoc = collection.find(eq(key, value)).first();
//convert myDoc to json object and return
return myDoc.toJson();
}