1

I'm new in MongoDb and I have to upload a file in MongoDB with a java program. I tried to write something but I do not know if it's the right way. Can someone help me? My difficulty is that the json file I have to upload is in a link address. can mongodb read and upload the document to a database through java language? I load the code below. Thank you.

import java.io.IOException;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;


public class mongodb {

public static void main (String args []) throws IOException {

    MongoClient mongo = null;
    MongoDatabase db = null;

    try {
        /**** Connect to MongoDB ****/
        mongo = new MongoClient("localhost", 27017);

        /**** Get database ****/
        db = mongo.getDatabase("db_plant");

        System.out.println("Successfully connected to database");           
    } catch (Exception e) {
        System.err.println( e.getClass().getName() + ": " + e.getMessage() );
    }

    DBCollection collection = db.getCollection("plants");

    final String URL = "https://www.plants.usda.gov/java/downloadData?fileName=plantlst.txt&static=true";
    String json = getTextFromUrl(URL);

    DBObject dbObject = (DBObject)JSON.parse(json);
    collection.insert(dbObject);

    DBCursor cursorDocJSON = collection.find();
    while (cursorDocJSON).hasNext() {
        System.out.println(cursorDocJSON).next();
    }
    collection.remove(new BasicDBObject();
}

private static String getTextFromUrl(String uRL) {
    // TODO Auto-generated method stub
    return null;
}

}

2
  • what error you are getting , mention that too. Commented Oct 6, 2017 at 10:38
  • At line 41: DBCollection collection = db.getCollection("plants"); Multiple markers at this line: - Debug Current Instruction Pointer - Type mismatch: cannot convert from MongoCollection<Document> to DBCollection Commented Oct 6, 2017 at 10:40

1 Answer 1

2

You are using the old API. If you use the Mongo java driver 3.X, the correct api is :

MongoCollection<Document> collection = database.getCollection("plants");

Document dbObject = Document.parse(json);

MongoCursor<Document> cursor = collection.find().iterator();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.