Query the most recent entries in a collection in Java - java

This mongodb query below returns the most recent entries to a collection
db.RSS.find().limit(6).sort({$natural:-1}).pretty()
Does anyone know how to implement this query in Java?

Using Mongo-Java Driver, this code is an example:
MongoClient client = new MongoClient("localhost",27017);
MongoDatabase db = client.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("RSS");
FindIterable<Document> it = collection.find().limit(6).sort(new Document().append("$natural", -1));
MongoCursor<Document> cursor = it.iterator();
while(cursor.hasNext()){
Document doc = cursor.next();
System.out.println(doc.toJson());
}

Related

Combine two mongoDB queries in Java

Below is the code I have:
//Creating a mongo client and connecting to the database and getting the collection from the table in database
MongoClient mongoClient = new MongoClient("000.1.1.26", 27017);
MongoDatabase databases = mongoClient.getDatabase("DBName");
System.out.println("Connected to the database successfully");
MongoCollection<Document> collection = databases.getCollection("TableName");
// Retrieving Column-wise data for fieldName from database
BasicDBObject searchQuery = new BasicDBObject();
FindIterable<Document> testColumn=collection.find().projection(Projections.fields(Projections.include("fieldName"), Projections.excludeId()));
//We have to run this command(Here I have merged 2 commands )
AggregateIterable<Document> iterDoc = collection.aggregate(Arrays.asList(Aggregates.group("$Id", Accumulators.max("logDate", 1)), project(Projections.fields(Projections.include("fieldName"), Projections.excludeId()))));
The above joint query is giving me below error:
The method project(Bson) is undefined for the type
Any help for this?

How to get data from MongoDB version 3.4 using Java?

I am trying to collect data from my mongodb in java, I need to use select query and put it in jtextarea. Select Query will be filled with combo box element.
Here is the code:
/**** Connect to MongoDB ****/
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
MongoClient mClient = new MongoClient(connectionString);
/**** Get database ****/
MongoDatabase db = mClient.getDatabase("productDB");
mClient.getAddress();
/**** Get collection / table from 'productDB' ****/
MongoCollection<Document> tableCollection = db.getCollection("local");
/**** Find and display ****/
Document whereQuery = new Document();
whereQuery.put("Product Category",categoryCB.getSelectedIndex());
MongoCursor<Document> cursor = tableCollection.find(whereQuery);
mClient.close();
In tableCollection.find shows:
cannot convert from FindIterable to MongoCursor
Is there any way to do this differently?
You are trying to receive a FindIterable object in a MongoCursor reference.
Change thetype of the reference variable 'cursor' from MongoCursor to FindIterable or its supertype MongoIterable.
FindIterable<Document> cursor = tableCollection.find(whereQuery);
(or)
MongoIterable<Document> cursor = tableCollection.find(whereQuery);
I have found code for this problem and it works, main part is in code below
mClient = new MongoClient(connectionString);
db = mClient.getDatabase("Your Database Name");
tableCollection = db.getCollection("Your Table Name");
whereQuery = new Document();
whereQuery.put("Your Attribute", typeCB.getSelectedItem().toString());
iterator=tableCollection.find(whereQuery);
cursor = iterator.iterator();
while (cursor.hasNext())
{
/*put your code here*/
}

writing mongoDB syntax

hey guys how to write this mongoDB syntax to java
db.users.find( { user_id: /bc/ },{user_name:/bc/},{age:/2/} )
my source is
BasicDBObject sortOrder = new BasicDBObject();
MongoClient mongoClient;
DB db;
DBCollection table;
DBCursor cursor = null;
mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("stackoverflow");
boolean auth = db.authenticate("aku","kamu".toCharArray());
table = db.getCollection("questions");
cursor = table.find();
while (cursor.hasNext()) {
DBObject object = cursor.next();
out.print(object.get("title"));
answer = rn.nextInt(8) + 0;
}
any solution guys?
i am newbie on using mongoDB
DBObject idMatch = new BasicDBObject("user_id","bc");
DBObject usernameMatch = new BasicDBObject("user_name",bc);
DBObject ageMatch = new BasicDBObject("age",2);
DBObject andAll = new BasicDBObject("$and", Arrays.asList(existence, firstNotMatch, secondNotMatch));
//calling table.find will get you what you wanted.
table.find(andAll);
If you want to 'OR' the conditions, just replace $and with $or.
note that the above code is not tested properly and you may need to modify it a bit to make it work.
Your question is not clear, but i hope i helped.

How to use $and operator in mongodb - java driver

How do we query for mongo using logical AND($and),
Example :
collection : Subject
From collection subject I need to get all the records satisfying the condition,
totalmarks!=10 and totalmarks!=15.
Equivalent in java driver.
List<DBObject> criteria = new ArrayList<DBObject>();
criteria.add(new BasicDBObject("totalmarks", new BasicDBObject("$ne", 10)));
criteria.add(new BasicDBObject("totalmarks", new BasicDBObject("$ne", 15)));
DBCursor dbCursor = collection.find(new BasicDBObject("$and", criteria));
Alternatively, for newer versions, you can use Bson object as a filter.
mongoDatabase = mongoClient.getDatabase("DBName");
MongoCollection<Document> col = mongoDatabase.getCollection("CollectionName");
Bson filter = Filters.and(
Filters.ne("totalmarks", 5),
Filters.ne("totalmarks",15));
MongoCursor<Document> cursor = col.find(filter).iterator();

How to identify document in MongoDB in Java

I am wondering if MongoDB provide some good schema for identifying documents in the database. Suppose I have initialized a database like this:
public static void main(String[] args) {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("testdb");
DBCollection coll = db.getCollection("mycollection");
BasicDBObject document = new BasicDBObject();
document.put("name", "Mike");
document.put("age", 25);
coll.insert(document);
}
Now How can I get the "document" inserted in the database? I already know a key/value pair query can locate the document, like:
BasicDBObject query = new BasicDBObject();
query.put("name", "Mike");
DBObject dbObj = coll.findOne(query);
Is there another way other than this kind of key/value pair query to identify the document?
If you want to identify a collection, you can do it by match the collection name:
DBCollection coll = db.getCollection("mycollection");
I hope there is something like this to identify the document. Any suggestion?
If you look in the document object after the coll.insert(document); you will find that a _id field was added by the driver. You can use this field/value to query for the exact document since MongoDB enforces there must be an _id field and it must be unique.
Putting this all together:
public static void main(String[] args) {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("testdb");
DBCollection coll = db.getCollection("mycollection");
BasicDBObject document = new BasicDBObject();
document.put("name", "Mike");
document.put("age", 25);
coll.insert(document);
System.out.println(document.get("_id"));
BasicDBObject query = new BasicDBObject();
query.put("_id" , document.get("_id"));
DBObject retrieved = collection.findOne(query);
System.out.println(retrieved);
}

Categories

Resources