MongoDB - Query by 2dsphere returns zero results - java

I wish to obtain a list of documents from a MongoDB collection by geospatial index. I have indexed the collection by 2dsphere
db.getCollection("Info").ensureIndex(new BasicDBObject("location", "2dsphere"), "geospatial");
A document in the Info collection look like this
{ "_id" : ObjectId("52631572fe38203a7388ebb5"), "location" : { "type" : "Point", "coordinates" : [ 144.6682361, -37.8978304 ] }
When I query the Info collection by the coordinates [ 144.6682361, -37.8978304 ], I am getting zero collections returned.
I am using JAVA API to perform the action. My JAVA code is below
DBCollection coll1=db.getCollection("Info");
BasicDBObject locQuery = new BasicDBObject();
locQuery.put("near", loc);
locQuery.append("maxDistance", 3000);
locCursor =coll1.find(locQuery);
System.out.println("LOCCURSOR"+locCursor.size());
The locCursor.size() returns always 0. Not sure where I am missing. At the same time, I am not getting any errors. It just gives me 0 documents returned. Any ideas Mongo users? Thanks for your time and help.

You can directly pass the value of your co-ordinates into your query:
double lat_lng_values[] = {144.6682361, -37.8978304};
BasicDBObject geo = new BasicDBObject("$geometry", new BasicDBObject("type","Point").append("coordinates",lat_lng_values));
BasicDBObject filter = new BasicDBObject("$near", geo);
filter.put("$maxDistance", 3000);
BasicDBObject locQuery = new BasicDBObject("location", filter);
System.out.println(locQuery);

Related

Mongo Query of Record by Array Object Field Value Using Java

I have collection called 'jobs' with a document :
{
"_id": "4bb131682d0682845098eabe",
"jobId": "1403610",
"refmdList": [
{
"_id": "4bb11af1f8d48284e0b2ef87",
"addrIdx": 1,
"type": "primary"
}
],
"status": "Created in J4",
}
And java code is used to find that job document using:
private DBCursor getRefMdCursor(String refId)
{
DB db = JDatabase.getDatabase();
BasicDBObject search = new BasicDBObject();
search.put("refmdList._id", refId);
DBCollection col = db.getCollection("jobs");
DBCursor cur = col.find(search);
return cur;
}
This is very slow and the refmdList._id is not indexed. Is the solution to index this array object field to speed it up or is there something problematic with the DBCursor code above?
DBCursor class is from mongodb/mongo-java-driver/3.4.3/mongo-java-driver-3.4.3.jar
An array's sub-document field can be indexed, and these indexes are called a Multikey indexes. See Index Arrays with Embedded Documents.
The field refmdList._id can be indexed. It can improve the performance of queries using that field as filter criteria.
About the Java code:
The MongoDB Java driver you are using is of older version (3.4.3), and there is a latest version available (3.12.0). Also, the Java code can be changed to use the newer APIs; see examples at Find Operations.

How to custom search for text query in mongodb?

I'm new in mongodb. I have following data as a JSON format in mongodb. I need to search the bookLabel or the shortLabel for the book and it should show me all the information about the book. For example: if I query for 'Cosmos' it'll show all the description about the book, like: bookLabel, writer, yearPublish, url. How can I do that in java? Need query, please help.
"Class":"Science",
"Description":[
{
"bookLabel":"Cosmos (Mass Market Paperback)",
"shortLabel":"Cosmos",
"writer":"Carl Sagan",
"yearPublish":[
"2002"
],
"url":"https://www.goodreads.com/book/show/55030.Cosmos"
},
{
"bookLabel":"The Immortal Life of Henrietta Lacks",
"shortLabel":"Immortal Life",
"writer":"Rebecca Skloot",
"yearPublish":[
"2010, 2011"
],
"url":"https://www.goodreads.com/book/show/6493208-the-immortal-life-of-henrietta-lacks"
}
],
"Class":"History",
"Description":[
{
"bookLabel":"The Rise and Fall of the Third Reich",
"shortLabel":"Rise and Fall",
"writer":"William L. Shirer",
"yearPublish":[
"1960"
],
"url":"https://www"
}
]
}
With MongoDB Java Driver v3.2.2 you can do something like this:
FindIterable<Document> iterable = collection.find(Document.parse("{\"Description.shortLabel\": {$regex: \"Cosmos\"}"));
This returns all documents containing Cosmos in the Description.shortLabel nested field. For an exact match, try this {"Description.shortLabel": "Cosmos"}. Replace shortLabel with bookLabelto search the bookLabel field. Then you can do iterable.forEach(new Block<Document>()) on the returned documents. To search both bookLabel and shortLabel, you can do a $or{}. My syntax could be wrong so check the MongoDB manual. But this is the general idea.
For this, you can use MongoDB's Text Search Capabilities. You'll have to create a text index on your collection for that.
First of all create a text index on your collection on fields bookLabel and shortLabel.
db.books.createIndex({ "Description.bookLabel" : "text", "Description.shortLabel" : "text" })
Note that this is done in the Mongo shell
Then
DBObject command = BasicDBObjectBuilder
.start("text", "books")
.append("search", "Cosmos")
.get();
CommandResult result = db.command(command);
BasicDBList results = (BasicDBList) result.get("results");
for(Object o : results) {
DBObject dbo = (DBObject) ((DBObject) o).get("obj");
String id = (String) dbo.get("_ID");
System.out.println(id);
}
Haven't really tested this. But just give it a try. Should work.

MongoDB - How to find and append / find and upsert both document and fields

In Mongo, is there a built-in way to update a document and instead of replacing all contents of the query document, to update those nodes which are the same and append those which do not exist in the original document.
For example, imagine I insert the following document into my collection:
{
"name" : "Goku",
"level" : 9000
}
Now, at some later point, I wish to update my existing document with the following document I received:
{
"name" : "Goku",
"son" : "Gohan"
}
Ideally, I would like a way to perform an update and produce the following document:
{
"name" : "Goku",
"level" : 9000,
"son" : "Gohan"
}
The standard case is to overwrite the existing document with the new document (as it should be). However, is there a built-in or clever way to achieve the result above without first finding the first document, appending onto it, and then performing an update?
Thanks.
-- EDIT --
#pennstatephil has the correct answer below. Just in case anyone's is helped by this, here's an implementation of this example in Java as of driver version 2.12.0:
String json = "{'name' : 'Goku', 'level' : 9000 }";
DBObject document = (DBObject) JSON.parse(json);
BasicDBObject update = new BasicDBObject("$set", document);
BasicDBObject query = new BasicDBObject().append("name", document.get("name"));
collection.findAndModify(query, null, null, false, update, false, true);
json = "{'name' : 'Goku', 'son' : 'Gohan'}";
document = (DBObject) JSON.parse(json);
update = new BasicDBObject("$set", document);
query = new BasicDBObject().append("name", document.get("name"));
collection.findAndModify(query, null, null, false, update, false, true);
I believe findAndModify and $set (on the update clause) is what you're looking for.

Remove and Add new array into the JSON object using MongoDB

I have JSON object :
{ "_id" : "1", "_class" : "com.model.Test", "projectList" : [ {
"projectID" : "Spring", "resourceIDList" : [ "Mark","David" ] },
{ "projectID" : "MongoDB", "resourceIDList" : [ "Nosa ] }
I need to be able to remove the resourceIDList for Project "Spring" and assign a new ResourceIDList.
The ResourceIDList is just List
Whenever I try to use the following,nothing is updated at DB:
Query query = new Query(where("_id").is("1").and("projectID").is("Spring"));
mongoOperations.updateMulti( query,new Update().set("ressourceIDList", populateResources()), Test.class);
Replacing the resourceIDList in the embedded document matching {"projectList.projectID":"Spring"} may be accomplished in the JavaScript shell like so:
(I like to start with the JS shell, because it is less verbose than Java and the syntax is relatively straightforward. Examples with JS can then be applied to any of the language drivers.)
> db.collection.update({_id:"1", "projectList.projectID":"Spring"}, {$set:{"projectList.$.resourceIDList":["Something", "new"]}})
The documentation on using the "$" operator to modify embedded documents may be found in the "The $ positional operator" section of the "Updating" documentation:
http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator
There is more information on embedded documents in the "Dot Notation (Reaching into Objects)" Documentation:
http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29
The above may be done in the Java Driver like so:
Mongo m = new Mongo("localhost", 27017);
DB db = m.getDB("test");
DBCollection myColl = db.getCollection("collection");
ArrayList<String> newResourceIDList = new ArrayList<String>();
newResourceIDList.add("Something");
newResourceIDList.add("new");
BasicDBObject myQuery = new BasicDBObject("_id", "1");
myQuery.put("projectList.projectID", "Spring");
BasicDBObject myUpdate = new BasicDBObject("$set", new BasicDBObject("projectList.$.resourceIDList", newResourceIDList));
myColl.update(myQuery, myUpdate);
System.out.println(myColl.findOne().toString());
If you have multiple documents that match {"projectList.projectID" : "Spring"} you can update them at once using the multi = true option. With the Java driver it would look like this:
myColl.update(myQuery, myUpdate, false, true);
In the above, "false" represents "upsert = false", and "true" represents "multi = true". This is explained in the documentation on the "Update" command:
http://www.mongodb.org/display/DOCS/Updating#Updating-update%28%29
Unfortunately, I am not familiar with the Spring framework, so I am unable to tell you how to do this with the "mongoOperations" class. Hopefully, the above will improve your understanding on how embedded documents may be updated in Mongo, and you will be able to accomplish what you need to do with Spring.

MongoDB and Java: Query doesn't return results

I'm using the MongoDB Java driver, and can't seem to get a query to work. I have a collection named "Questions", which has entries that look like:
{
"question" : "how are you",
"category" : "personal",
"processed" : false,
"training" : true
}
When running the Mongo command line client, the query
db.questions.find()
or
db.questions.find({"processed" : false, "training" : true})
results are returned as expected; however, my java code does the following:
DBObject queryObj = new BasicDBObject();
queryObj.put("processed", false);
queryObj.put("training", isTrain);
DBObject updateObj = new BasicDBObject();
queryObj.put("processed", true);
DBCursor cursor = mongoCollection.find(queryObj).limit(NUM_TO_LOAD);
mongoCollection.update(queryObj, updateObj);
and the cursor that is returned to me is empty/the update doesn't make any changes. If I remove the queryObj argument from the call to find, results are once again returned as expected. Am I doing something wrong here?
Thanks,
Chris Covert
looks like, you used the wrong variable on line 6. Shouldn't it be updateObj, instead of queryObj?
Hope isTrain is a boolean, and got correctly initiated with a value (true/false).

Categories

Resources