MongoClient mongo = new MongoClient();
DB db = mongo.getDB("mytest");
DBCollection col = db.getCollection("testt");
//read example
DBObject query = BasicDBObjectBuilder.start("$gte", "06/01/2016 00:00:00").add("$lte", "10/01/2016 00:00;00").get();
DBCursor cursor = col.find(query);
while(cursor.hasNext()) {
System.out.println("docc:");
System.out.println(cursor.next());
}
I am getting below exception while selecting data from MongoDB in Java.
com.mongodb.MongoQueryException: Query failed with error code 2 and
error message 'unknown top level operator: $gte' on server
127.0.0.1:27017 at com.mongodb.operation.FindOperation$1.call(FindOperation.java:493) at
com.mongodb.operation.FindOperation$1.call(FindOperation.java:483) at
com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:241)
at
com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:214)
at
com.mongodb.operation.FindOperation.execute(FindOperation.java:483)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:80)
at com.mongodb.Mongo.execute(Mongo.java:818) at
com.mongodb.Mongo$2.execute(Mongo.java:805) at
com.mongodb.DBCursor.initializeCursor(DBCursor.java:851) at
com.mongodb.DBCursor.hasNext(DBCursor.java:152) at
MongoFetch.main(MongoFetch.java:55)
Well you query does not mention the field you are querying on - just the range, therefore mongoDB does not really know what to do. Try something like that
...
BasicDBObject query = new BasicDBObject();
query.put("yourDateField", BasicDBObjectBuilder.start("$gte", fromDate).add("$lte", toDate).get());
DBCursor cursor = col.find(query);
...
Related
I'm trying to follow this post to create a "contains" query in Java. The problem is it's giving me an error.
At the moment i have the following code:
MongoClient mongoClient = null;
DBCursor cursor = null;
mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("bd-films");
DBCollection coll = db.getCollection("films");
DBObject query = new BasicDBObject({"title" : {$regex : "name"}});
cursor = coll.find(query);
The error it gives me is in the 'query' line:
Syntax error on token ""title"", invalid Label
Syntax error, insert ";" to complete Statement
Syntax error on token ")", delete this token
I use the cursor for inserting it into a JTable.
Driver: mongo-java-driver-3.4.2
Thanks in advance.
Use new Document and MongoCollection api's for java driver 3.x version.
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase db = mongoClient.getDatabase("bd-films");
MongoCollection<Document> coll = db.getCollection("films");
List<Document> results = coll.find(Filters.regex("title", "name")).into(new ArrayList<>())
For accesssing MongoCursor,
FindIterable<Document> results = coll.find(Filters.regex("title", "name"));
MongoCursor<Document> cursor = results.iterator();
I want to get ID by a matching name in mongoDB in Java.
That's my code:
MongoClient mongo = new MongoClient();
DB db = mongo.getDB("test");
DBCollection groupTable = db.getCollection("Items");
searchQuery.put("name", "John");
DBCursor cursor = groupTable.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
But it shows the whole row containt the name John, what I want is the ID not the whole thing.
{"list":[{"timestamp":{"$date":"2014-08-01T08:37:54.058Z"},"name":John,"_id":{"$oid":"53db5045ccf2b2399e0e6128"},"created":{"$date":"2014-08-}
Any help?
Thanks
It's very simple, just select the id...
while (cursor.hasNext()) {
System.out.println(cursor.next().get("_id"));
}
I am new to mongodb java api. I am trying to perform queries to my database. I ve read the database found the collections in it and I want to retrieve characteristics of users. My code:
ServerAddress serverAdr;
serverAdr = new ServerAddress(".. .. .., ...);
Twitter twitter = null;
MongoOptions options = new MongoOptions();
options.connectionsPerHost = 10;
MongoClient mongoClient = new MongoClient(.. ... ...", ...);
DB db = mongoClient.getDB("trendSetters");
System.out.println("Connect to database successfully");
//JSONObject content = getJSONFromFile("user.json");
Mongo mongo = null;
Set<String> colls = db.getCollectionNames();
mongo = new Mongo(serverAdr, options);
mongo.setWriteConcern(WriteConcern.SAFE);
DB db_se = mongo.getDB("iti_se");
DBCollection incollection = db_se.getCollection("cms_users_unique");
DBCollection outcollection = db_se.getCollection("cms_users_features");
for (String s : colls) {
System.out.println(s);
}
Now I want to perform queries to retrieve from all ids the usernames for example. How is it possible to do so in java mongodb API?
EDIT: What i ve tried
BasicDBObject query = new BasicDBObject();
DBCursor cursor;
query = new BasicDBObject("followers", new BasicDBObject("$gt", 1));
cursor = incollection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
However, it doesnot return nothing.
You asked: "I want to perform queries to retrieve from all ids the usernames for example."
To retrieve all documents from collection you can use find() method of the DBCollection.
DBCursor cursor;
cursor = incollection.find();
After that, you can get the field value by its name for each document as below
while(cursor.hasNext()){
System.out.println(cursor.next().get("username"));
}
If you need to add more criterias to query documents:
BasicDBObject query1;
DBCursor cursor;
query1 = new BasicDBObject("age", new BasicDBObject("$gt", 25));
cursor = incollection.find(query1);
while(cursor.hasNext()){
System.out.println(cursor.next().get("username"));
}
DBCollections objects have method find which takes mainly a DBObject argument. For instance, if you want to find users with age > 50 this can help you.
query = new BasicDBObject("age", new BasicDBObject("$gt", 50));
cursor = incollection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
BasicDBObject take first argument, that is a field, and second argument that is another BasicDBObject or a value. With composition of these objects you can build any query.
I recommend you take a look at MongoDB Documentation, it's pretty good.
Mongo Java Driver http://docs.mongodb.org/ecosystem/drivers/java/
See Javadoc. http://api.mongodb.org/java/current/
I have following codes:
mongoClient = new MongoClient( "localhost" , 27017 );
db = mongoClient.getDB("hcm");
DBCollection coll = db.getCollection("segment_cell_details");
BasicDBObject query = new BasicDBObject("cell_x", cell_x).append("cell_y", cell_y);
DBCursor cursor = coll.find(query);
Next, I want to add DBCursor in memcached :
c = new MemcachedClient(AddrUtil.getAddresses("localhost:11211"));
c.add("Key", 3600, cursor);
Then, System prints out "Non-serializable object error"
So, how can I add the result of query to memcached ?
The cursor is an iterator that lazily loads the results. You need to add the results not the iterator. I recommend adding them as serialised JSON.
while (cursor.hasNext())
c.add("key",3600,cursor.next().toString());
I have to write a simple MongoDB query using java but am not able to do it.
The mongo query looks like this:
db.yourCollection.find({"$where" : "this.startDate < this.endDate"})
I have to write the above query using the QueryBuilder class. But am not able to do it in MongoDB java driver.
BasicDBObject document = new BasicDBObject();
document.put("id", 1001);
document.put("intValue", 1200);
document.put("updateValue", 2100);
DBObject query = QueryBuilder.start("intValue").lessThan("updateValue").get();
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println("Result : -"+cursor.next());}
The above code does not return any results. But if changed to updateValue into 2100 it is giving result. My question here is lessThan takes object as input parameter. Then how can I pass document field as an input parameter?
Ideally your mongoDB query should be like this: -
db.yourCollection.find({"startDate": {$lt: endDate}})
which can be written in Java like this: -
BasicDBObject query = new BasicDBObject("startDate", new BasicDBObject("$lt", endDate);
DBCursor cursor = coll.find(query);
You can take a look at Official Tutorial
If you want to use QueryBuilder, you can do it like this: -
DBObject query = QueryBuilder.start("startDate").lessThan("endDate").get();
DBCursor cursor = coll.find(query);
QueryBuilder helps construct complex queries to retrieve data from a collection in mongo db.
You can use the QueryBuilder like this.
BasicDBObject document = new BasicDBObject();
QueryBuilder qb = new QueryBuilder();
qb.or(new QueryBuilder().put("starting_date").is(null).put("ending_date").is(null).get(),
new QueryBuilder().put("starting_date").lessThanEquals("ending_date").get());
document.putAll(qb.get());
DBCursor cursor = getDbCollection().find(document)
QueryBuilder qb = new QueryBuilder(), instantiates a new QueryBuilder.
The logic build by the QueryBuilder in the example above is; (starting date = null and ending date = null) or (starting date <=ending date)
document.putAll(qb.get()) adds the logic constructed to the DBObject.