2

I am trying to fetch a particular field in mongo. Now this field is included in many objects so we might need to run an array also I need to narrow it down to some particular text. I was able to get all the fields but I don't seem to be able to get just one field.

    MongoClient mongo = new MongoClient(PAH TO MONGO);

    System.out.println(mongo.getDatabaseNames());  
    DB db= mongo.getDB(DB NAME); 
    DBCollection coll = db.getCollection(COLLECTION NAME);
    BasicDBObject whereQuery = new BasicDBObject();

DBCursor cursor= coll.find(whereQuery); 

    while (cursor.hasNext())
    { 
        System.out.println(cursor.next());
    }

IS ALSO TRIED

    MongoClient mongo = new MongoClient(PAH TO MONGO);

    System.out.println(mongo.getDatabaseNames());  
    DB db= mongo.getDB(DB NAME); 
    DBCollection coll = db.getCollection(COLLECTION NAME);
    BasicDBObject searchQuery= new BasicDBObject();
             //FIELD NAME
             searchQuery.getString("Url");  
           DBCursor cursor= coll.find(searchQuery); 

    while (cursor.hasNext())
    { 
        System.out.println(cursor.next());
    }

I also need to filter the data with some partial text lets say a url field with http://yahoo.com/@#%##$, but this is a partial url so I need to make sure I get yahoo.com and whatever is after it, because there is other data besides just yahoo.com.

The reason why I need this is because I need to deposit the url I get from mongo into a variable and then use that variable in a loop to run through each url and run automated testing.

It will be great if someone can help me out.

Thanks,

Mediha

1 Answer 1

3

The cursor.next() statement returns a DBObject instance. Therefore, you can assign it to a variable and then invoke the DBObject#get(String key) method.

Also, a cast to the BasicDBObject class may be necessary, if you want to have a MongoDB specific bson object.

For example:

while (cursor.hasNext()) { 
    BasicDBObject next = (BasicDBObject) cursor.next();
    Object someField = next.get("someField");
    //more stuff
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks A lot this was simpler than I thought I will just figure out the filteration.
@Madi, you can accept my asnwer if you find it useful. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.