I have a MongoCollection
in which I assign a collection.
I\'m trying to find a user by his id.
user = (Document) usersCollection
If you using IP to connect to MongoDb here how you do it change HEREYOURIP
import static com.mongodb.client.model.Filters.eq;
public static Document GetDocumentFromDataBase(String dataBase,String DBcollection,String field, String value) {
MongoClient mongoClient = new MongoClient( " HEREYOURIP ",27017 );
MongoDatabase database = mongoClient.getDatabase(dataBase);
MongoCollection collection = database.getCollection(DBcollection);
Document myDoc = collection.find(eq(field, value)).first();
mongoClient.close();
return myDoc;}
edited found other way do it
public static String GetFromDB(String DATABASE_NAME,String collectionName, String field, String value) {
String valueBack;
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id", new ObjectId(value));
MongoClient mongoClient = new MongoClient(System.getenv("HERE_YOUR_DB_IP"), 27017);
MongoDatabase database = mongoClient.getDatabase(DATABASE_NAME);
MongoCollection collection = database.getCollection(collectionName);
Document myDoc = collection.find(whereQuery).first();
if (myDoc != null) {
valueBack = myDoc.toString();
mongoClient.close();
return valueBack;
}
mongoClient.close();
return null;
}