I am new to mongodb and i have the following code
import com.mongodb.*;
import com.mongodb.Block;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;
import static java.util.Arrays.asList;
public class getAssets{
public static void main( String args[] ){
Block<Document> printBlock = new Block<Document>() {
#Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
MongoClient mongoClient = new MongoClient("localhost",27017);
MongoDatabase database = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
MongoCollection<Document> coll = database.getCollection("asset");
BasicDBList statusList = new BasicDBList();
statusList.add("1");
statusList.add("2");
statusList.add("3");
DBObject statusInClause = new BasicDBObject("$in", statusList);
BasicDBList idList = new BasicDBList();
idList.add("123");
DBObject siteIdInClause = new BasicDBObject("$in", idList);
DBObject fields = new BasicDBObject("asset.status", statusInClause);
fields.put("asset.siteid", siteIdInClause);
DBObject unwind = new BasicDBObject("$unwind", "$asset");
DBObject match = new BasicDBObject("$match", fields);
AggregateIterable<Document> aggr = coll.aggregate(asList(unwind, match));
aggr.forEach(printBlock);
mongoClient.close();
}
}
And i am getting the following error while compling
C:\MongoDB\java>javac -cp .;mongo-java-driver-3.4.1.jar getAssets.java
getAssets.java:46: error: no suitable method found for aggregate(List<DBObject>)
AggregateIterable<Document> aggr = coll.aggregate(asList(unwind, match));
^
method MongoCollection.<TResult>aggregate(List<? extends Bson>,Class<TResult>) is not applicable
(cannot instantiate from arguments because actual and formal argument lists differ in length)
method MongoCollection.aggregate(List<? extends Bson>) is not applicable
(actual argument List<DBObject> cannot be converted to List<? extends Bson> by method invocation conversion)
where TResult is a type-variable:
TResult extends Object declared in method <TResult>aggregate(List<? extends Bson>,Class<TResult>)
1 error
Note : Using mongo 3.4.1
New Code :
import com.mongodb.*;
import com.mongodb.Block;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;
import static java.util.Arrays;
import static java.util.Arrays.asList;
public class getAssets{
public static void main( String args[] ){
Block<Document> printBlock = new Block<Document>() {
#Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
MongoClient mongoClient = new MongoClient("localhost",27017);
MongoDatabase database = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
MongoCollection<Document> coll = database.getCollection("asset");
Document unwind = new Document("$unwind", "$dp.asset");
Document match = new Document("$match", new Document("$dp.asset.status", new Document("$in", new String[]{"ACTIVE", "LIMITEDUSE", "OPERATING"})).
append("$dp.asset.siteid", new Document("$in", new String[]{"BEDFORD"})));
AggregateIterable<Document> aggr = coll.aggregate(Arrays.asList(unwind, match));
aggr.forEach(printBlock);
mongoClient.close();
}
}
Compiles with no error but runtime error
Exception in thread "main" java.lang.NoSuchMethodError: org.bson.BsonDocument.clone()Lorg/bson/BsonDocument;
at com.mongodb.connection.ClientMetadataHelper.createClientMetadataDocument(ClientMetadataHelper.java:146)
at com.mongodb.connection.ClientMetadataHelper.createClientMetadataDocument(ClientMetadataHelper.java:136)
at com.mongodb.connection.InternalStreamConnectionFactory.<init>(InternalStreamConnectionFactory.java:41)
at com.mongodb.connection.DefaultClusterableServerFactory.create(DefaultClusterableServerFactory.java:68)
at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:360)
at com.mongodb.connection.SingleServerCluster.<init>(SingleServerCluster.java:54)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:114)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.<init>(Mongo.java:293)
at com.mongodb.Mongo.<init>(Mongo.java:288)
at com.mongodb.Mongo.<init>(Mongo.java:284)
at com.mongodb.MongoClient.<init>(MongoClient.java:179)
at com.mongodb.MongoClient.<init>(MongoClient.java:156)
at com.mongodb.MongoClient.<init>(MongoClient.java:146)
at getAssets.main(getAssets.java:20)
For me , I resolved this error by using mongodb driver 3.6.4
Add this in your dependency(gradle for example)
dependencies {
implementation 'org.mongodb:mongodb-driver:3.6.4'
}
I am using IntelliJ IDEA to manage my dependencies and I noticed that I had the MongoDB bson library listed twice in my libraries (once as org.mongo:bson:3.0.0 and also as org.mongo:bson:Latest). I deleted the "Latest" entry and the error went away.
Related
As a step towards familiarising myself with MongoDB, I started to create simple Java Classes to perform CRUD in MongoDB. I was able to establish connection with MongoDB. Nevertheless, when I try to iterate through the MongoDB collection, I'm getting errors. Implemented Java class is shared here.
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.Iterator;
import org.bson.Document;
public class ReadMongo {
public static void main( String args[] ) {
//Creating a MongoDB client
com.mongodb.client.MongoClient mongo = MongoClients.create("mongodb://localhost:27017");
//Connecting to the database
MongoDatabase database = mongo.getDatabase("myDB");
//Creating a collection object
MongoCollection<Document> collection = database.getCollection("myGrid");
//Retrieving the documents
FindIterable<Document> iterDoc = collection.find();
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Below I've shared the error log.
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.internal.operation.SyncOperations.<init>(Lcom/mongodb/MongoNamespace;Ljava/lang/Class;Lcom/mongodb/ReadPreference;Lorg/bson/codecs/configuration/CodecRegistry;Lcom/mongodb/WriteConcern;Z)V
at com.mongodb.client.internal.MongoCollectionImpl.<init>(MongoCollectionImpl.java:106)
at com.mongodb.client.internal.MongoDatabaseImpl.getCollection(MongoDatabaseImpl.java:132)
at com.mongodb.client.internal.MongoDatabaseImpl.getCollection(MongoDatabaseImpl.java:127)
at ReadMongo.main(ReadMongo.java:14)
The line #14 corresponds to MongoCollection<Document> collection = database.getCollection("myGrid"); line.
I still don't know what's wrong with the above code. Nevertheless, I was able to solve this issue following these resources: (i) resource 1 and (ii) resource 2. The final working solutions is as follows.
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class MongoDB {
public static MongoClient mongoClient;
public static MongoDatabase database;
public static void main(String[] args) {
mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
database = mongoClient.getDatabase("myDB");
FindIterable<Document> mydatabaserecords = database.getCollection("myGrid").find();
MongoCursor<Document> iterator = mydatabaserecords.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println(iterator.next());
}
}
}
I'm storing a data from android studio into mongodb,storing the data is successful but retrieving is somewhat hard.
even though I find a way to read the data in mongodb it gives json objects in the server side.
I need a way to display that json objects into the textview of an android.
package com.example.prabhakaran.toiletfeedbacksystem;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class readDB {
public static void main(String[] args) {
comments(args);
feedback(args);
neo_checklist(args);
robin_checklist(args);
}
public static void comments(String[] args) {
MongoClient client = new MongoClient("172.20.9.122", 28018);
MongoDatabase database = client.getDatabase("raji");
MongoCollection<Document> collection = database
.getCollection("testcollection");
List<Document> documents = collection.find().into(
new ArrayList<Document>());
for(Document document : documents){
System.out.println(document);
}
}
public static void feedback(String[] args) {
MongoClient client = new MongoClient("172.20.9.122", 28018);
MongoDatabase database = client.getDatabase("raji");
MongoCollection<Document> collection = database
.getCollection("Comments");
List<Document> documents = collection.find().into(
new ArrayList<Document>());
for(Document document : documents){
System.out.println(document);
}
}
public static void neo_checklist(String[] args) {
MongoClient client = new MongoClient("172.20.9.122", 28018);
MongoDatabase database = client.getDatabase("raji");
MongoCollection<Document> collection = database.getCollection("neo");
List<Document> documents = collection.find().into(new ArrayList<Document>());
for(Document document : documents){
System.out.println(document);
}
}
public static void robin_checklist(String[] args) {
MongoClient client = new MongoClient("172.20.9.122", 28018);
MongoDatabase database = client.getDatabase("raji");
MongoCollection<Document> collection = database
.getCollection("robin");
List<Document> documents = collection.find().into(
new ArrayList<Document>());
for(Document document : documents){
System.out.println(document);
}
}
}
Output
Document{ {_id=5c5020c08d5509385e1ac8f4, Value=robin, done=clean
toilet_bowl, Created_Date=Tue Jan 29 15:15:36 IST 2019} }
I have this type of data in the run window on android studio,but I want to have those data in the android app in textview or something.
so assist me in this issue,Thanks in advance.
I've saved Set<String> into mongodb as array and after that I want to load it again into Set<String>. How to do this?
My try returns exception:
package Database;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import java.util.HashSet;
import java.util.Set;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class StackOverflow {
public static void main(String[] args) {
// insert something to mongo:
final String URI = "mongodb://localhost:27017";
final String DB = "StackOverflowQuestion";
final String COLLECTION = "eqDoesntExcist";
MongoClientURI connection = new MongoClientURI(URI);
MongoClient mongo = new MongoClient(connection);
MongoDatabase database = mongo.getDatabase(DB);
MongoCollection<Document> collection = database.getCollection(COLLECTION);
Set<String> namesOfTroysKids = new HashSet<>();
namesOfTroysKids.add("Paul");
namesOfTroysKids.add("Jane");
namesOfTroysKids.add("Mark");
namesOfTroysKids.add("Ivona");
Document doc = new Document("name", "Troy").append("height", 185).append("kids", namesOfTroysKids);
collection.insertOne(doc);
// read something from mongo
FindIterable<Document> findIt = collection.find(eq("name", "Troy")).projection(fields(include("kids")));
Document d = findIt.first();
Set<String> kids = (Set<String>) d; // ERROR !!!
///Exception in thread "main" java.lang.ClassCastException: org.bson.Document cannot be cast to java.util.Set
//at Database.StackOverflow.main(StackOverflow.java:45)
}
}
There was method toArray() but it is for DBObject which is depreciated.
The document returned by your query is:
{
"_id": {
"$oid": "_id_value_"
},
"kids": [
"Mark",
"Ivona",
"Paul",
"Jane"
]
}
That obviously can not be implicitly coerced into a set. Its now just a matter of obtaining the kids from the document as a list and instantiating a Set from it:
public static void main(String [] args) throws Exception {
final String URI = "mongodb://localhost:27017";
final String DB = "StackOverflowQuestion";
final String COLLECTION = "eqDoesntExcist";
MongoClientURI connection = new MongoClientURI(URI);
MongoClient mongo = new MongoClient(connection);
MongoDatabase database = mongo.getDatabase(DB);
MongoCollection<Document> collection = database.getCollection(COLLECTION);
Set<String> namesOfTroysKids = new HashSet<>();
namesOfTroysKids.add("Paul");
namesOfTroysKids.add("Jane");
namesOfTroysKids.add("Mark");
namesOfTroysKids.add("Ivona");
Document doc = new Document("name", "Troy").append("height", 185).append("kids", namesOfTroysKids);
collection.insertOne(doc);
// read something from mongo
FindIterable<Document> findIt = collection.find(Filters.eq("name", "Troy")).projection(Projections.include("kids"));
Document d = findIt.first();
System.out.println("doc: " + d.toJson());
List<String> kidsList = (List<String>) d.get("kids", List.class);
Set<String> kidsSet = new HashSet<>(kidsList);
System.out.println("kids: " + kidsSet);
}
Basically an Iterable type is something that is meant to loop through. If you open a cursor using the Iterable type the only way to assign it to a java data type is to grab one iteration. You have done this by using the first method which will grab the first document returned by your query, note that if that is your intention you can use sort to control which Document is returned.
Below is the code. When i do this i generally do whatever i need to with the data one by one unless i need the entire dataset before i start my processing.
Set<String> kids = new Set<String>;
for(Document kidDoc : collection.find(eq("name", "Troy"))){
kids.add(kidDoc.getString("kids")))
}
I've found in mongodb tutorial for java about how to query from mongo collection but the eq which they use doesn't work for me! Do you know how to filter documents from a collection with mongo and java?
This is my try:
package Database;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class StackOverflow {
public static void main(String[] args) {
// insert something to mongo:
final String URI = "mongodb://localhost:27017";
final String DB = "StackOverflowQuestion";
final String COLLECTION = "eqDoesntExcist";
MongoClientURI connection = new MongoClientURI(URI);
MongoClient mongo = new MongoClient(connection);
MongoDatabase database = mongo.getDatabase(DB);
MongoCollection<Document> collection = database.getCollection(COLLECTION);
Document doc = new Document("name", "Troy").append("height", 185);
collection.insertOne(doc);
doc = new Document("name", "Ann").append("height", 175);
collection.insertOne(doc);
// read something from mongo
FindIterable<Document> findIt = collection.find(eq("name", "Troy"));
// ERROR!!! the method eq(String, String) is undefined!
mongo.close();
}
}
I want something like:
SELECT * from eqDoesntExcist WHERE name = "Troy"
You can use an eq Filter there as:
Bson bsonFilter = Filters.eq("name", "Troy");
FindIterable<Document> findIt = collection.find(bsonFilter);
or else to make it look the way doc suggests include a static import for the method call Filters.eq
import static com.mongodb.client.model.Filters.eq;
and further use the same piece of code as yours :
FindIterable<Document> findIt = collection.find(eq("name", "Troy")); // static import is the key to such syntax
you can not do this:
collection.find(eq("name", "Troy"));
because the compiler will expect in your class StackOverflow a method with the name eq and this is not what you need..
what you are looking for is defined in the Filter class
public static <TItem> Bson eq(String fieldName, Item value)
so it may be
collection.find(Filters.eq("name", "Troy"));
I am getting this error on the last line in code below:
The type org.bson.conversions.Bson cannot be resolved. It is indirectly referenced from required .class files, I am using Mongo JavaDriver 3.0.2
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
public class InsertDriver {
public static void main(String[] args)
{
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("postsdb");
DBCollection collection = db.getCollection("posts");
BasicDBObject doc1 = new BasicDBObject();
doc1.put("user", "Mike");
doc1.put("sports", "soccer");
doc1.put("tweet", "Hi..");
//String json = JSON.serialize( doc1);
//BasicDBObject bson = (BasicDBObject) JSON.parse( json );
List<BasicDBObject> docs = new ArrayList<BasicDBObject>();
docs.add(doc1);
collection.insert(docs); //ERROR HERE
}
}
Had the same issue. I've solved it by downloading the bson jar and adding it to the search path.
The Mongodb documentation states the following:
You can also download the jars directly from sonatype. Note:
mongodb-driver requires the following dependencies: bson and
mongodb-driver-core