$slice mongoDB Java - 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.

Related

How do I implement this MongoDB aggregation in Java

I have the following working MongoDB aggregation shell command:
db.followrequests.aggregate([{
$match: {
_id: ObjectId("551e78c6de5150da91c78ab9")
}
}, {
$unwind: "$requests"
}, {
$group: {
_id: "$_id",
count: {
$sum: 1
}
}
}]);
Which returns:
{ "_id" : ObjectId("551e78c6de5150da91c78ab9"), "count" : 7 }
I need to implement this in Java, I am trying the following:
List<DBObject> aggregationInput = new ArrayList<DBObject>();
BasicDBObject match = new BasicDBObject();
match.put("$match", new BasicDBObject().put("_id",new ObjectId(clientId)));
aggregationInput.add(match);
BasicDBObject unwind = new BasicDBObject();
unwind.put("$unwind", "$requests");
aggregationInput.add(unwind);
BasicDBObject groupVal = new BasicDBObject();
groupVal.put("_id", "$_id");
groupVal.put("count", new BasicDBObject().put("$sum", 1));
BasicDBObject group = new BasicDBObject();
group.put("$group", groupVal);
aggregationInput.add(group);
AggregationOutput output = followRequestsCol.aggregate(aggregationInput);
for (DBObject result : output.results()) {
System.out.println(result);
}
I am getting an exception:
mongodb the match filter must be an expression in an object.
Can you please help me identify the error in the above code. Thanks!
Try to print the value of aggregationInput and you will realise that .put() does not return a BasicDBObject but just the previous value associated to the key you update. Therefore, when you do:
match.put("$match", new BasicDBObject().put("_id",new ObjectId(clientId)));
You are actually setting $match to null, as new BasicDBObject().put("_id",new ObjectId(clientId)) returns null.
Update you code to something like:
List <DBObject> aggregationInput = new ArrayList <DBObject> ();
BasicDBObject match = new BasicDBObject();
BasicDBObject matchQuery = new BasicDBObject();
matchQuery.put("_id", new ObjectId());
match.put("$match", matchQuery);
aggregationInput.add(match);
BasicDBObject unwind = new BasicDBObject();
unwind.put("$unwind", "$requests");
aggregationInput.add(unwind);
BasicDBObject groupVal = new BasicDBObject();
groupVal.put("_id", "$_id");
groupVal.put("count", new BasicDBObject().put("$sum", 1));
BasicDBObject group = new BasicDBObject();
group.put("$group", groupVal);
aggregationInput.add(group);
AggregationOutput output = followRequestsCol.aggregate(aggregationInput);
for (DBObject result : output.results()) {
System.out.println(result);
}
Or, slightly more readable, use the fluent BasicDBObjectBuilder:
final DBObject match = BasicDBObjectBuilder.start()
.push("$match")
.add("_id", new ObjectId())
.get();
aggregationInput.add(match);
And it should work fine.
Each {} must be new DBObject. Use also .append(key,value) method to make more elegant.
Try this:
List<DBObject> pipeline = new ArrayList<DBObject>(Arrays.asList(
new BasicDBObject("$match", new BasicDBObject("_id",
new ObjectId("551e78c6de5150da91c78ab9"))),
new BasicDBObject("$unwind", "$requests"),
new BasicDBObject("$group",
new BasicDBObject("_id","$_id").append("count", new BasicDBObject("$sum", 1)))));
AggregationOutput output = followRequestsCol.aggregate(pipeline);
for (DBObject result : output.results()) {
System.out.println(result);
}
This is the final working version, based on the above suggestions
// Use mongodb aggregation framework to determine the count of followers
Integer returnCount = 0;
List aggregationInput = new ArrayList();
BasicDBObject match = new BasicDBObject();
BasicDBObject matchQuery = new BasicDBObject();
matchQuery.put("_id", new ObjectId(clientId));
match.put("$match", matchQuery);
aggregationInput.add(match);
BasicDBObject unwind = new BasicDBObject();
unwind.put("$unwind", "$requests");
aggregationInput.add(unwind);
BasicDBObject groupVal = new BasicDBObject();
groupVal.put("_id", null);
BasicDBObject sum = new BasicDBObject();
sum.put("$sum", 1);
groupVal.put("count", sum);
BasicDBObject group = new BasicDBObject();
group.put("$group", groupVal);
aggregationInput.add(group);
AggregationOutput output = followRequestsCol.aggregate(aggregationInput);
for (DBObject result : output.results()) {
returnCount = (Integer) result.get("count");
break;
}
return returnCount;

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 use aggregation in Mongo db Java driver with $match and $in?

How to convert below query into Java code for Mongo Java driver?
db.post.aggregate(
[
{ $match : {"name" :{'$in': ["michael", "jordan"] } }},
{ $group : { _id : "$game.id" , count : { $sum : 1 } } }
]
)
My function is not working:
DBObject match = new BasicDBObject('$match', new BasicDBObject("name", names));
The $in operator takes and array or list of arguments, so any list will basically do. But you need to form the corresponding BSON. Indenting your code helps to visualize:
BasicDBList inArgs = new BasicDBList();
inArgs.add("michael");
inArgs.add("jordan");
DBObject match = new BasicDBObject("$match",
new BasicDBObject("name",
new BasicDBObject("$in", inArgs )
)
);
DBObject group = new BasicDBObject("$group",
new BasicDBObject("_id","$game.id").append(
"count", new BasicDBObject("$sum",1)
)
);
According to the Aggregation Documentation, your query should look like:
DBObject match = new BasicDBObject('$match', new BasicDBObject('name', new BasicDBObject('$in', names)));

Java MongoDB Query

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 to find value of innerattributes in mongodb?

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")

Categories

Resources