Java MongoDB Query - java

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

Related

Retrieve only the queried element in an object array in MongoDB using java

Suppose we have the following documents in a MongoDB collection:
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"shapes":[
{
"shape":"square",
"color":"blue"
},
{
"shape":"circle",
"color":"red"
}
]
},
{
"_id":ObjectId("562e7c594c12942f08fe4193"),
"shapes":[
{
"shape":"square",
"color":"black"
},
{
"shape":"circle",
"color":"green"
}
]
}
And the MongoDB query is
db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});
Can someone tell me how to write it in Java?
I am using:
List<BasicDBObject> obj = new ArrayList<>();
obj1.add(new BasicDBObject("shapes.color", "red"));
List<BasicDBObject> obj1 = new ArrayList<>();
obj2.add(new BasicDBObject("shapes.$", "1"));
BasicDBObject parameters1 = new BasicDBObject();
parameters1.put("$and", obj1);
DBCursor cursor = table.find(parameters1,obj2).limit(500);
and I am not getting anything.
The syntax of the Mongo Shell find function is:
db.collection.find(query, projection)
query document Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).
projection document Optional. Specifies the fields to return in the documents that match the query filter.
When translating this for execution by the Mongo Java driver you need to construct separate BasicDBObject instances for;
the query
the projection
Here's an example:
MongoCollection<Document> table = ...;
// {"shapes.color": "red"}
BasicDBObject query = new BasicDBObject("shapes.color", "red");
// {_id: 0, 'shapes.$': 1}
BasicDBObject projection = new BasicDBObject("shapes.$", "1").append("_id", 0);
FindIterable<Document> documents = table
// assign the query
.find(query)
// assign the projection
.projection(projection);
System.out.println(documents.first().toJson());
Given the sample documents included in your question the above code will print out:
{
"shapes": [
{
"shape": "circle",
"color": "red"
}
]
}
This is identical to the output from db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});.

How to use $in operator in mongodb with two fields in java

I would like to retrieve the following information:
select names from database where address like 'colombo' and age>20;
but for MongoDB in Java. Essentially, it should return all names that contain the word colombo ang age greater than 20 in them. I know that there is the $in operator in MongoDB, but how do I do the same in Java, using the Java driver? I've been trying to look for it everywhere but am getting nothing. I've tried:
query = new BasicDBObject("names", new BasicDBObject("$in", "colombo"), new BasicDBObject("age", "$gt20"));
But it didn't worked :( Please help!
Try this
BasicDBObject query = new BasicDBObject("names", new BasicDBObject("$in", Arrays.asList("colombo")));
query.append("age", new BasicDBObject("$gt", 20));
FindIterable<Document> find = collection.find(query);
MongoCursor<Document> iterator = find.iterator();
Document doc = null;
while (iterator.hasNext()) {
doc = iterator.next();
System.out.println(doc);
}
The $in operator will not be suitable for such as you can only use it to match values that are in an array or to search for documents where the value of a field equals any value in a specified array.
In your case you need a $regex operator to fulfil the query by performing a SQL LIKE operation:
db.collection.find({
"names": { "$regex": /colombo/, "$options": "i" },
"age": { "$gt": 20 }
})
or
db.collection.find({
"names": /colombo/i },
"age": { "$gt": 20 }
})
which can be implemented in Java as
Pattern pattern = Pattern.compile("colombo", Pattern.CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject("names", pattern)
.append("$age", new BasicDBObject("$gt", 20));
DBCursor result = coll.find(query);
If using the 3.0.x and newer drivers:
Document regx = new Document();
regx.append("$regex", "(?)" + Pattern.quote("colombo"));
regx.append("$options", "i");
Document query = new Document("names", regx).append("$age", new Document("$gt", 20));
FindIterable<Document> iterable = db.getCollection("coll").find(query);

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

$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