Confusion about mongodb java driver [duplicate] - java

This question already has an answer here:
Java MongoDB: What is the difference between com.mongodb.DB and com.mongodb.client
(1 answer)
Closed 6 years ago.
I am a beginner to MongoDB and I'm playing around with it using the JAVA driver.
I have the following code
MongoClient client = new MongoClient();
DB d = client.getDB("world");
DBCollection c = d.getCollection("zips");
DBCursor cursor = c.find();
Now my question is that I want to use a simple cursor to go through the documents. The getDB() method is deprecated but it works fine. In the documentation it's mentioned that getDB can be replaced with MongoClient.getDatabase(); but getDatabase() returns a MongoDatabase not a DB.
Can someone point out the correct way to make a DBCursor without using any deprecated method. Thanks.
PS: I know there are frameworks like morphia, jongo etc but please keep them out of this discussion. I want to currently resort only to the JAVA driver.
EDIT: The difference is about getting a cursor in the JAVA driver not between DB and MongoClient

Yes. Thats true. you can replace getDB with getDatabase. this is how you can use it.
/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
MongoDatabase mydatabase = mongoClient.getDatabase("mydatabase");
/**** Get collection / table from 'testdb' ****/
// if collection doesn't exists, MongoDB will create it for you
FindIterable<Document> mydatabaserecords = mydatabase.getCollection("collectionName").find();
MongoCursor<Document> iterator = mydatabaserecords.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
// do something with document
}
Example:
So lets say that your document is something like below:
{
"name": "Newton",
"age": 25
}
Then fields can be fetched as below
while (iterator.hasNext()) {
Document doc = iterator.next();
String name = doc.getString("name");
int age = doc.getInteger("age");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
I hope this clears your doubt.

Related

How to retrieve an element of an arraylist from a Mongodb collection using java?

I have the following code and my aim is to retrieve the documents which have the given tags.
String myText = "It is the first #example and is very #important";
ArrayList<String> tags = textProcessor.getTags(myText);
try {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("myFirstDatabase");
DBCollection table = db.getCollection("firstCollection");
BasicDBObject document = new BasicDBObject();
document.put("Text", myText);
document.append("tags", tags);
table.insert(document);
/**** Find and display ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("tags", "#important");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
It does not work, because the tagsis an array and I am searching for an element in the array. How can I retrieve the documents which have the given tag (in this case "important") directly?
I know that I can extract all the tags of all documents and then compare them in a loop. But I would like to do that directly.
In the meantime, I am completely new to mongodb. If there is a better way to insert tags in the database (so that, its retrieving is easier), I would be grateful to know.
Thanks in advance,
Mongodb list can be queried through a single string query just fine, you should check the textProcessor.getTags and check the data in the mongodb. I also suggest you to use spring-data-mongodb since it is much simpler and easier to learn.

How to insert a document at first position in MongoDB

By default, mongodb adds documents to the end of collection. However, I want them to be added at the first position in the collection. The code I have is,
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("test");
DBCollection collection = db.getCollection("lwjsons");
BasicDBObject document = new BasicDBObject();
collection.insert(dbObject);
Use sort when querying.
Just use db.collection.find().sort({_id:-1}).
You are saving documents to collection. It is not like push or unshift in javascript.

How to auto-increment non-numeric ID in mongo db

I want to auto-increment 'Project_ID' using mongo DB. I need to put 'Project_ID' value as 'demo_1', so using this value when I trying to auto-increment this value, it showing error: can not increment non numeric id.
public static Object getNextSequence(String Project_ID) throws Exception{
// MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Now connect to your databases
// DB db = mongoClient.getDB("demo");
DB db=ConnectToDB.getConnection();
Properties prop = new Properties();
InputStream input = null;
input = Demo.class.getClassLoader().getResourceAsStream("config.properties");
prop.load(input);
String col=prop.getProperty("COLLECTION_DEMO");
DBCollection collection = db.getCollection("counters");
BasicDBObject find = new BasicDBObject();
find.put("_id", Project_ID);
BasicDBObject update = new BasicDBObject();
update.put("$inc", new BasicDBObject("seq", 1));
DBObject obj = collection.findAndModify(find, update);
db.getMongo().close();
return obj.get("seq");
}
Please let me know what is the issue there or what is the possible way to achieve this. Thanks.
Your explanation of what you're trying to autoincrement does not match the code, never mind the error. You're code is trying to autoincrement seqin a document keyed by Project_ID, in this case demo_1.
I ran your code although I got no errors, it is possible you don't have a "seed" record to findAndModify(). Try running this to create your seed:
db.counters.drop();
db.counters.insert({_id: "demo_1", seq: NumberInt("0")});
then run your code.
Also: You are connecting and closing the connection with each call to getNextSequence. That will be really slow. I recommend you open the DB and capture the collection in main()and close it upon exit.

MongoDB Data reading from database

I am new to mongodb and I am using a database with a single document in a collection called "Counts". Entering that data is done by the code itself and after entering that data, the document looks like in the first picture.
After that I use the below code sample to read data.
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "OneMedia" );
System.out.println("Connect to database successfully");
DBCollection coll = db.getCollection("Counts");
System.out.println("zzzzzzzzzzzzzzzzzz");
DBCursor curs = coll.find();
Iterator<DBObject> fields = curs.iterator();
while(fields.hasNext()){
BasicDBList List = (BasicDBList) fields.next().get("counts");
BasicDBObject object = (BasicDBObject) List.get(0);
Object value = object.get("comments_count"); /
System.out.println("comments - " + value.toString());
}
Every time I run that code to read data, the document in the collection duplicates and creates another document inside same collection.
Can some one please help me with this.
When you running the code you added a new document. as you say. Since it added to the database it is there even you closed the programe. But if you need to delete all the data in the collection you can use coll.drop(); before you add new document into the database.

Queries in java mongodb API

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/

Categories