How to find value of innerattributes in mongodb? - java

I am new to mongoDB.And I want to get all values of time in the json like:
{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"}, "LoginRequest" : { "Time" : "11-06-2012 11:59:33", "innerAttr4" : "innerValue4"} }
{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113cb"}, "LoginRequest" : { "Time" : "11-06-2012 12:34:05", "innerAttr4" : "innerValue4"} }
After searching i found to use the dot notation. But the dot notation is not working for me in java. Can someone tell me how to do this?
I used the dot notation in this manner. But it returns null.
String selectedCollection = "user01"; //WILL CONTAIN THE SELECTED USERNAME
DBCollection coll = db.getCollection(selectedCollection);
ArrayList<String> result = new ArrayList<String>();
//DBObject obj = coll.findOne("LoginRequest.Time");
BasicDBObject query = new BasicDBObject();
BasicDBObject field = new BasicDBObject();
field.put("LoginRequest.Time", 1);
DBCursor cursor = coll.find(query,field);
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
result.add(obj.getString("LoginRequest.Time"));
System.out.println(obj.getString("LoginRequest.Time") );
}
It works fine if i am replacing LoginRequest.Time with LoginRequest everywhere. Thanks for help.

(BasicDBObject(obj.get("LoginRequest"))).getString("Time")

Related

Java Jersey MongoDB GET sublist

I am developing an API to get position list in a BSON looks like below.
{
"_id" : ObjectId("59512a4ca33bc80248fb1435"),
"id" : NumberLong(1),
"locationId" : NumberLong(17),
"position" : [
{
"latitude" : 12342.0,
"longitude" : 1232342.0,
"time" : "on May 04 09:51:52 CDT 2009"
},
{
"latitude" : 12342.0,
"longitude" : 1232342.0,
"time" : "on May 04 09:51:52 CDT 2009"
}
]
}
In my Employee class I have a method called setPosition(List<Position> positions) Is there a way to pass a list to this function by getting position array from BSON using `emp.get("positions")
Below is the getAllEmployees() funtion where I can't set the position by converting the BSOn into a list
public List<Employee> getAllEmployees() {
DBObject query = new BasicDBObject();
DBCursor cursor = employeeCollection.find(query);
System.out.println("cursor.count : " + cursor.count());
List<Employee> list = new ArrayList<Employee>();
while (cursor.hasNext()) {
DBObject emp = cursor.next();
Employee employee = new Employee();
employee.setId((long) emp.get("id"));
employee.setLocationId((long) emp.get("locationId"));
DBObject pos = (DBObject) emp.get("position");
System.out.println("pos : " +pos);
List<Position> positions = *HERE COMES THE PROBLEM!!!!!*
employee.setPosition(positions);
list.add(employee);
}
return list;
}
Any suggestions how to pass the positions array from mongodb directly to setPosition function?
Finally I got this to work. Below is the getAllEmployees() function. The solution was to use BasicDBList instead of BDObject.
public List<Employee> getAllEmployees() {
DBObject query = new BasicDBObject();
DBCursor cursor = employeeCollection.find(query);
System.out.println("cursor.count : " + cursor.count());
List<Employee> list = new ArrayList<Employee>();
while (cursor.hasNext()) {
DBObject emp = cursor.next();
Employee employee = new Employee();
employee.setId((long) emp.get("id"));
employee.setLocationId((long) emp.get("locationId"));
BasicDBList positions = (BasicDBList) emp.get("position");
for (Object position : positions) {
Position pos = new Position();
pos.setLatitude((double) ((DBObject) position).get("latitude"));
pos.setLongitude((double) ((DBObject) position).get("longitude"));
pos.setTime((String) ((DBObject) position).get("time"));
employee.getPosition().add(pos);
}
list.add(employee);
}
return list;
}

How to Query MongoDB Using Child Nodes in Java

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());
}

MongoDb Polygon Search Query returns no result

I have problems regarding a Polygone Search in my MongoDB.
I have a document structure like:
Object:{id,type,...,
data:{
name,
loc:{
lng:xxx
lat:yyy
type:Point}}}
I have an 2d Index on "data.loc".
My query in java code is:
DBCollection coll = database.getCollection(type);
BasicDBList points = new BasicDBList();
points.add(bbox.getNe());
points.add(bbox.getSe());
points.add(bbox.getSw());
points.add(bbox.getNw());
points.add(bbox.getNe());
BasicDBList parentList = new BasicDBList();
parentList.add(points);
DBObject query = new BasicDBObject("data.loc",
new BasicDBObject("$geoWithin",
new BasicDBObject("$geometry", new BasicDBObject("type","Polygon")
.append("coordinates", parentList))));
The Debuger tells me that the query is for example
{ "data.loc" : { "$geoWithin" : { "$geometry" : { "type" : "Polygon" ,
"coordinates" : [ [ [ 48.240553 , 16.451597] , [ 48.162751 ,
16.451597] , [ 48.162751 , 16.303968] , [ 48.240553 , 16.303968] , [ 48.240553 , 16.451597]]]}}}}
But after typing
DBCursor cursor = coll.find(query);
try {
while(cursor.hasNext()) {
data.add(cursor.next().get("data"));
}
} finally {
cursor.close();
}
return data;ยด
data is allways null.
Can anyone find any problems in my approach or does maybe someone have a better approach? In fact I want to do a boundingbox search on my database.
Thank you for your help!
Best regards
Daniel
Okay, so the Java MongoDB driver query for the points in the polygone for a GeoJson strcuture like this is
BasicDBList points = new BasicDBList();
points.add(bbox.getNe());
points.add(bbox.getSe());
points.add(bbox.getSw());
points.add(bbox.getNw());
points.add(bbox.getNe());
BasicDBList parentList = new BasicDBList();
parentList.add(points);
Set<Object> data = new CopyOnWriteArraySet<Object>();
DBObject query = new BasicDBObject("geometry",
new BasicDBObject("$geoWithin",
new BasicDBObject("$geometry", new BasicDBObject("type","Polygon")
.append("coordinates", parentList))));
System.err.println(query);

How to create a List<String> from a BasicDBList in mongodb in Java?

The JSON stored in mongodb database is of form
{
"genre": ["Action", "Animation", "Drama"],
"movie_id": 1
}
I have to get a list of genres. Sorry if the question is lame. I'm kinda new to Java and mongodb.
i propose the below code to solve your issue:
MongoClient mongo = new MongoClient( "localhost" , 27017 );
DB db = mongo.getDB(dbName);
DBCollection collection = db.getCollection(collectionName);
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("movie_id", id);
DBObject document = collection.findOne(whereQuery);
BasicDBList list = (BasicDBList) document.get("genre");
List<String> res = new ArrayList<String>();
for(Object el: list) {
res.add((String) el);
}
Look:
{
"genre": ["Action", "Animation", "Drama"],
"movie_id": 1,
"attributes" : [
{
"name" : "name 1",
"value" : "value 1"
}, {
"name" : "name 2",
"value" : "value 2"
}
]
}
You can use:
DBObject dbObject = (DBObject) object.get("attributes");
BasicDBList list = new BasicDBList();
for (String key : dbObject.keySet()) {
list.add(dbObject.get(key));
}
List<String> listArray = new ArrayList<String>();
for (Object object : list) {
listArray.add(object.toString());
}
and
DBObject dbObject = (DBObject) object.get("genre");
List<String> listArray = new ArrayList<String>();
for (String key : dbObject.keySet()) {
list.add(((DBObject) dbObject.get(key)).toString());
}
You can too (but, maybe don't working):
BasicDBList list = (BasicDBList) object.get("attributes");
List<String> listArray = new ArrayList<String>();
for (Object object : list) {
listArray.add(((DBObject) object).toString());
}
and
BasicDBList list = (BasicDBList) object.get("genre");
List<String> listArray = new ArrayList<String>();
for (Object object : list) {
listArray.add(object.toString());
}
DBObject channelDBObject = new BasicDBObject();
System.out.println("genre");
String genre = bufferReader.readLine();
String[] temp = genre.split(",");
int i=0;
BasicDBList genreDBList = new BasicDBList();
DBObject genreDBObject = null;
while(i<temp.length){
genreDBObject = new BasicDBObject();
genreDBObject.put("genre",temp[i++]);
genreDBList.add(genreDBObject);
}
channelDBObject.put("genre",genreDBList.toArray());
System.out.println("Movie Id");
String MovieId = bufferReader.readLine();
channelDBObject.put("MovieId",Integer.parseInt(MovieId));
dBCollection.insert(channelDBObject);
DBCursor dbcursor = dBCollection.find();
while (dbcursor.hasNext())System.out.println(dbcursor.next());
}

$slice mongoDB Java

How can I make this query in Java
db.comments.find({ "hsID.$id" { "$oid" : "4fe71a50e7e9f22ae5fb96bf"}} , {commentList: { $slice : [ 2 , 2]}});
This the code I am doing
BasicDBObject query = new BasicDBObject();
BasicDBObject allFields = new BasicDBObject();
ObjectId objectId = new ObjectId(objId);
query.put("{hsID.$id", objectId);
Integer[] sliceInt = { startIndex, pageSize };
query.put(
"commentList",
new BasicDBObject().append("$slice", sliceInt));
DBCursor resultsCursor = CommentColl.find(allFields,query);
and the output is
And the output is
query = { "{hsID.$id" : { "$oid" : "4fe71a50e7e9f22ae5fb96bf"} , "commentList" : { "$slice" : [ 2 , 2]}}
Thanks for your help
You need to separate the query from the fields you want returned. Try something more like this:
BasicDBObject query = new BasicDBObject("hsID.$id", new ObjectId(objId));
BasicDBObject fields = new BasicDBObject(
"commentList",
new BasicDBObject("$slice", new int[] { startIndex, pageSize }));
DBCursor resultsCursor = CommentColl.find(query, fields);
Notice also that I removed the opening curly brace that you had preceding hsid.$id.

Categories

Resources