Question:
I'm new to mongo, I'm trying to do an insert in the bank but it gives a problem when 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 cannot be converted to com.mongodb.DBObject[]) method com.mongodb.DBCollection.insert(java.util.List) is not applicable (argument mismatch; com.mongodb.BasicDBObject cannot be converted to java.util.List) )
Answer:
The installation to work would be two .jar
:
NetBeans Development Environment
Code worked after installing 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 deprecated, and soon it won't work. Then use the getDatabase
method, 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 IDEA development environment
There are also two .jar
Note: For this reason there are differences between Development Environments and installed packages and their particularities.