find in MongoCollection

后端 未结 5 1044
忘掉有多难
忘掉有多难 2020-12-20 13:54

I have a MongoCollection in which I assign a collection. I\'m trying to find a user by his id.

user = (Document) usersCollection         


        
5条回答
  •  旧时难觅i
    2020-12-20 14:30

    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;
    
        }
    

提交回复
热议问题