package com.mongodb;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.net.UnknownHostException;
public class InsertTest {
public static void main(String[] args) {
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient(connectionString);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MongoDatabase database = mongoClient.getDB("course");
MongoCollection<Document> collection = database.getCollection("writers");
Document doc = new Document("name", "Lamu")
.append("age", 30)
.append("profession", "Scientist");
collection.insertOne(doc);
}
}
“Error:(21, 51) java: incompatible types: com.mongodb.DB cannot be converted to com.mongodb.client.MongoDatabase”.
Hi Harsh,
The error is caused the use of the legacy DB from mongoClient.getDB("course").
Instead, please substitute with mongoClient.getDatabase("course"). See also MongoClient class description.
You may also find MongoDB Java Driver - Quick Start tutorial useful.
If you have further question, please provide which MongoDB Java Driver version you're using.
Regards,
Wan.
--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
For other MongoDB technical support options, see:https://docs.mongodb.com/manual/support/
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user+unsubscribe@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/b279c839-89a6-4279-aa76-b6902fc2ebc9%40googlegroups.com.