I have a MongoCollection<Document> in which I assign a collection.
I'm trying to find a user by his id.
user = (Document) usersCollection.find(new Document("_id", username));
with that I'm getting an error
java.lang.ClassCastException: com.mongodb.FindIterableImpl cannot be
cast to org.bson.Document
When I try
BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("_id", username);
usersCollection.find(query, fields);
I'm getting an error
The method find(Bson, Class) in the type MongoCollection is not applicable for the arguments (BasicDBObject, BasicDBObject)
Try to create a filter to pass to the find() method to get a subset of the documents in your collection. For example, to find the document for which the value of the _id field is test, you would do the following:
import static com.mongodb.client.model.Filters.*;
MongoClient client = new MongoClient();
MongoDatabase database = client.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("mycoll");
Document myDoc = collection.find(eq("_id", "test")).first();
System.out.println(myDoc.toJson());
Your issue is that you assume that the find() method returns a single Document. It doesn't. It returns a list of them.
In MongoDB 2 Java driver there was a method on the DBCollection class named findOne(). In the MongoDB 3 Java driver API, the findOne() method isn't there. So your new code for finding exactly one document becomes similar too this one:
collection.find(eq("_id", 3)).first()
where eq("_id", 3) is called a filter on your collection.
MongoCollection<Document> filterCriteriaDoc = mongoDatabase.getCollection("documentName");
Document filterDoc = new Document();
filterDoc.put("col1", "value");
filterDoc.append("col2", "value");
filterDoc.append("col2", "value");
Iterator<Document> iter = filterCriteriaDoc.find(filterDoc).iterator();
iter.next() can give you document .
If you using IP to connect to MongoDb here how you do it change HEREYOURIP
import static com.mongodb.client.model.Filters.eq;
public static Document GetDocumentFromDataBase(String dataBase,String DBcollection,String field, String value) {
MongoClient mongoClient = new MongoClient( " HEREYOURIP ",27017 );
MongoDatabase database = mongoClient.getDatabase(dataBase);
MongoCollection<Document> collection = database.getCollection(DBcollection);
Document myDoc = collection.find(eq(field, value)).first();
mongoClient.close();
return myDoc;}
edited found other way do it
public static String GetFromDB(String DATABASE_NAME,String collectionName, String field, String value) {
String valueBack;
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id", new ObjectId(value));
MongoClient mongoClient = new MongoClient(System.getenv("HERE_YOUR_DB_IP"), 27017);
MongoDatabase database = mongoClient.getDatabase(DATABASE_NAME);
MongoCollection<Document> collection = database.getCollection(collectionName);
Document myDoc = collection.find(whereQuery).first();
if (myDoc != null) {
valueBack = myDoc.toString();
mongoClient.close();
return valueBack;
}
mongoClient.close();
return null;
}
Do this -
MongoClient client = new MongoClient();
DBObject resultObject = new BasicDBObject("_id", username);
MongoDatabase database = client.getDatabase("DBNAME");
MongoCollection<Document> collection = database.getCollection("COLLECTION_NAME");
DBObject dbObject = new BasicDBObject("_id", username);
resultObject = collection.find(dbObject).next();
String result = resultObject.get(YOUR_COLOUM_NAME);
Related
I want to get max timestamp of a set of tags from MongoDb history database. Say the tag ids are 1,2,3,4,5 I want to check all records for these tags and get the timestamp of latest. My collection looks like this along with data:
My code is as follows:
protected Timestamp getMaxRealTimeHistoryTimestamp(List<Integer> tagIds)
{
try
{
MongoClient mongo = new MongoClient(m_connectionInfo.getHost(), m_connectionInfo.getPort());
//Connecting to the database
MongoDatabase database = mongo.getDatabase(m_connectionInfo.getDatabaseName());
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<>();
obj.add(new BasicDBObject("TAG_ID", new BasicDBObject("$in", tagIds)));
MongoCollection<Document> collection = database.getCollection("EM_HISTORY");
Document doc = collection.find(andQuery).sort(new Document("TIME_STAMP", -1)).first();
if(doc != null)
{
return new Timestamp(((Date) doc.get("TIME_STAMP")).getTime());
}
}
catch (Exception e)
{
if (Logger.isErrorEnabled())
Logger.error(e);
}
return null;
}
the doc variable has some strange row that is not even in the collection
What am I doing wrong here?
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<>();
obj.add(new BasicDBObject("TAG_ID", new BasicDBObject("$in", tagIds)));
You are never adding the query filters from obj back into your andQuery, so the code ends up querying the collection without any filter.
final DBObject group = new BasicDBObject("$group", groupFields);
DBObject sort = new BasicDBObject("$sort", new BasicDBObject("NAME", -1));
AggregateIterable <Document> aggregate = collection.aggregate((List<? extends Bson>) asList(group,sort));
That code is throwing this error:
could not parse error message: required: List
found: List
How can I resolve this?
You are mixing the java driver 2.x api with 3.x driver api.
MongoCollection, MongoDatabase, Document/Bson are 3.x classes whereas DBCollection, DB and BasicDBObject/DBObject are 2.x classes.
Looks like you are using 3.x driver, so you've to do something like below.
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("db");
MongoCollection<Document> collection = db.getCollection("collection");
BsonField id = Accumulators.first("ID", "$ID");
BsonField name = Accumulators.first("NAME", "NAME");
BsonField amount = Accumulators.sum("amount", "$amount");
Bson group = Aggregates.group("$NAME", id, name, amount);
Bson sort = Aggregates.sort(Sorts.descending("NAME"));
List<Document> results = collection.aggregate(Arrays.asList(group, sort)).into(new ArrayList<>());
More information here http://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/
In MongoDB how to print document in the form of key=value pairs from a java client after getting all documents in a List?
public static void main(String[] args){
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> coll = database.getCollection("criminal");
if (coll != null) {
List<Document> foundDocument = coll.find().into(new ArrayList<Document>());
Iterator<Document> itr = foundDocument.iterator();
while (itr.hasNext()) {
//System.out.println(itr.next());
//here toString() method is overriden in Document so output is displaying
}
}
Here,I'm trying to retrieve the status field if the name matches.How to use FindIterable instead of DBCursor.Can anyone please help me out ...
My code:
public String getStatus(String name) throws Exception{
MongoClient mongo = new MongoClient("localhost",27017);
MongoDatabase db = mongo.getDatabase("counter");
MongoCollection<Document> col = db.getCollection("status");
Document query = new Document();
query.put("name", name);
query.put("status", 1);
Document fields = new Document();
fields.put("status", 1);
fields.put("_id", 0);
DBCursor cursor = collection.find(query,fields);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
return "SUCCESS";
}
You simply load the cursor into a FindIterable object like so:
FindIterable<Document> docs = col.find(query);
if (docs == null) {
//no values found
}
for(Document doc : docs) {
//access documents e.g. doc.get()
}
You simply load the cursor and fetch the document into the Document. for more info visit https://dzone.com/articles/basic-java-crud-operations
DBCursor cursor = items.find(query);
while (cursor.hasNext()) {
Document document = cursor.next();
System.out.println(document.getString("identifier"));
}
I'm trying to query mongodb with java. The name of my collection is: reads. Here is an example of a specific document I'm querying for:
{
"_id" : {
"d" : "B66929932",
"r" : "15500304",
"eT" : ISODate("2014-09-29T12:03:00Z")
},
"v" : 169000,
"iT" : ISODate("2015-04-10T20:42:07.577Z")
}
I'm trying to query where r = 15500304, eT = 2014-09-29T12:03:00Z and v = 169000. I'm able to do this in mongo pretty easily:
db.reads.find({ "_id.r" : "15500304", "_id.eT" : ISODate("2014-09-29T12:03:00Z"), "$where" : "this.v == 169000;"}).pretty()
I'm unable to figure out how to structure this in java. So far I've got:
DBCollection collection = db.getCollection("reads");
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("_id.r", "15500304"));
obj.add(new BasicDBObject("_id.eT", "2014-09-29T12:03:00Z"));
obj.add(new BasicDBObject("v", 169000));
andQuery.put("$and", obj);
DBCursor cursor = collection.find(andQuery);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
My Question is: How do I query using these child nodes and return the matching document?
I'm unable to find any clear advice/examples online. Any and all advice is very appreciated.
You were close. Modify your query to:
DBCollection collection = db.getCollection("reads");
BasicDBObject query = new BasicDBObject();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String dateInString = "2014-09-29T12:03:00Z";
Date date = df.parse(dateInString);
query.append("status.name", "Expired")
.append("_id.eT", date)
.append("v", 169000);
Or using QueryBuilder:
DBObject query = QueryBuilder.start()
.put("_id.r").is("15500304")
.put("_id.eT").is(date)
.put("v").is(169000)
.get();
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}