I can not insert into MongoDB using Java

4

I'm new to mongo, I'm trying to make an insert in the bank but it's the problem at the time of inserting

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

    public class InsertDriver {
        public static void main(String[] args) throws UnknownHostException {
            DB dB = (new MongoClient("localhost", 27017)).getDB("realdatabase");
            DBCollection dBCollection = dB.getCollection("Channel");
            BasicDBObject basicDBObject = new BasicDBObject();
            basicDBObject.put("name", "guilherme");
            basicDBObject.put("state", "happy");
            dBCollection.insert(basicDBObject);

        }
    }
  

Error: (14, 21) java: no suitable method found for insert (com.mongodb.BasicDBObject)       method com.mongodb.DBCollection.insert (com.mongodb.DBObject ...) is not applicable         (argument mismatch; com.mongodb.BasicDBObject can not be converted to com.mongodb.DBObject [])       method com.mongodb.DBCollection.insert (java.util.List) is not applicable         (argument mismatch; com.mongodb.BasicDBObject can not be converted to java.util.List)

    
asked by anonymous 20.09.2016 / 04:30

1 answer

5

The installation to work would be two .jar :

NetBeans Development Environment

Code worked after the installation of these two packages:

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("realdatabase");        
DBCollection collection = db.getCollection("channel");
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("name", "guilherme");
basicDBObject.put("state", "happy");
collection.insert(basicDBObject);

But the getDB method is obsolete, and soon will not work. Then use the method getDatabase , MongoDatabase and MongoCollection<Document> which are the most current.

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
MongoDatabase database = mongoClient.getDatabase("realdatabase");                
MongoCollection<Document> collection = database.getCollection("channel");

Document doc = new Document();
doc.put("name", "somalia");
doc.put("state", "casado");

collection.insertOne(doc);

IntelliJ Development Environment

There are also two .jar

Installation Reference / strong>

Note: For this reason there are differences between Environments and the installed packages and their peculiarities.

    
20.09.2016 / 06:33