简体   繁体   中英

Insert a document JSON from URL in mongodb with java

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

}

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM