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;
}
Related
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());
}
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());
}
I have a structure like this in my database:
{
{
"document_id" : 35,
"transport" : ["car", "plane", "train", "boat"]
},
{
"document_id" : 36,
"transport" : ["car", "bike", "train"]
}
}
How would I do a search query to find a document/record with for example transport 'plane'?
Thanks for any help.
Steven
from MongoShell
db.find({transport:"plane"}) would do.
MongoDB will search the entire array to match the query in case the value is an array.
Using Java Driver.
Yous first get the Mongo collection
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "plane");
DBCursor cur = collection.find(dbo);
while (cur.hasNext()) {
list.add(JSONHelper.toJSON(cur.next().toMap()));
}
To search for an array containing an element, you can just check for that element against the array.
So, just using: -
db.collection.find({transport:"plane"})
would give you what you want.
Here's the implementation in Java: -
BasicDBObject doc = new BasicDBObject("document_id", 35)
.append("transport", new String[] {"car", "plane"});
BasicDBObject doc2 = new BasicDBObject("document_id", 36)
.append("transport", new String[] {"car"});
coll.insert(doc);
coll.insert(doc2);
DBObject query = new BasicDBObject("transport", "plane");
DBCursor cursor = coll.find(query, new BasicDBObject("_id", 0));
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
Output : -
{ "document_id" : 35 , "transport" : [ "car" , "plane"]}
#Document(collection = "document")
public class Transport {
private ObjectId document_id;
private ArrayList transport;
}
//
List<String> list = new ArrayList<String>();
list.add("car");
list.add("plane");
list.add("train");
list.add("boat");
Transport transport;
transport.setTransport(list);
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.
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")