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);
Related
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)));
This statement works fine in mongo console:
db.system_integrator.find( { person_name: { $in: [ "Mick Jagger", "Bob Dyla", "Tony Orlando" ] } } )
I'm trying to build equivalent one in java using QueryBuilder as following:
DBObject query = new BasicDBObject();
query.put(dbFieldName, "[ \"Mick Jagger\", \"Bob Dyla\", \"Tony Orlando\" ]");
qb.in( query );
however this way of building a query doesn't work. What I'm doing wrong here?
You can do this in Java as follows :
BasicDBList list = new BasicDBList();
list.add("Mick Jagger");
list.add("Bob Dyla");
list.add("Tony Orlando");
QueryBuilder qb = new QueryBuilder();
qb.put("person_name").in(list);
or
BasicDBList list = new BasicDBList();
list.add("Mick Jagger");
list.add("Bob Dyla");
list.add("Tony Orlando");
DBObject query = new BasicDBObject();
query.put("person_name", new BasicDBObject("$in", list));
I'm using mongo 2.2.3 and the java driver.
My dilemma, I have to $push a field and value into an array, but I cant seem to figure out how to do this. A sample of my data:
"_id" : 1,
"scores" : [
{
"type" : "homework",
"score" : 78.97979
},
{
"type" : "homework",
"score" : 6.99
},
{
"type" : "quiz",
"score" : 99
}
]
I can $push in the shell:
db.collection.update({_id:1},{$push:{scores:{type:"quiz", score:99}}})
but it's when I translate this into java I confuse my self and chuck my keyboard at a wall.
my java code (incomplete and wrong) so far:
DBObject find = new BasicDBObject("_id", 1);
DBObject push = new BasicDBObject("$push", new BasicDBObject(
"scores", new BasicDBObject()));
DBObject listItem = new BasicDBObject("scores", new BasicDBObject("type","quiz").append("score",99));
DBObject updateQuery = new BasicDBObject("$push", listItem);
myCol.update(findQuery, updateQuery);
Since mongodb-driver 3.1. there is a builder class com.mongodb.client.model.Updates with appropriate methods for each update case. In this case this would be:
Document score = new Document().append("type", "quiz")
.append("score",99);
collection.updateOne(eq("_id", "1"),Updates.addToSet("scores", score));
If you're more comforable with the query format of the shell, you may find it's easier to use JSON.parse to contstruct your DBObject for the $push:
import com.mongodb.util.JSON;
String json = "{$push:{scores:{type:'quiz', score:99}}}";
DBObject push = (DBObject) JSON.parse(json);
Using Jongo, you can do as in the shell:
db.collection.update({_id:1},{$push:{scores:{type:"quiz", score:99}}})
Becomes in Java:
collection.update("{_id:1}").with("{$push:{scores:{type:#, score:#}}}", "quiz", 99);
No fancy DBObject needed ;-)
MongoDB Java driver can simplify this. Use $each instead of $push.
$each mongodb reference document
Java sample -
BasicDBObject addressSpec = new BasicDBObject();
addressSpec.put("id", new ObjectId().toString());
addressSpec.put("name", "one");
BasicDBObject addressSpec2 = new BasicDBObject();
addressSpec2.put("id", new ObjectId().toString());
addressSpec2.put("name", "two");
List<BasicDBObject> list = new ArrayList<>();
list.add(addressSpec); list.add(addressSpec2);
UpdateResult updateOne = individualCollection.updateOne(Filters.eq("_id", "5b7c6b612612242a6d34ebb6"),
Updates.pushEach("subCategories", list));
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.