MongoDb in Java to find users - java

I have these three users in my DB with the following keys:
Jon-111
Jon-222
Jon-333
The code I wrote currently can only find one user in the DB by his key.
How can I return all these users?
public void getMongoDB() {
DB db = mongo.getDB("people");
DBCollection table = db.getCollection("users");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("key", "Jon-111"); // what do I do here to return all the 'Jon' users?
DBCursor cursor = table.find(searchQuery);
int dbSize = cursor.size(); // size is 1
while (cursor.hasNext()) {
logger.debug(""+cursor.next()+"\n");
}
logger.debug("users table");
}
Thanks in advance

If you want your search to be 'Starts with Jon', try:
searchQuery.put("key", java.util.regex.Pattern.compile("^Jon"));
You will need to use regex to do this kind of query, as shown in my example.
Some more examples for your benefit:
'Ends with Jon':
searchQuery.put("key", java.util.regex.Pattern.compile("Jon$"));
'Contains Jon':
searchQuery.put("key", java.util.regex.Pattern.compile(".*Jon.*"));

You can use regex Pattern to pass in the value. Something like below:
searchQuery.put("key", java.util.regex.Pattern.compile("Jon-\\.*"));

Related

Do not retrieve all columns with Elastic search query

I have an Elastic search query and I would like to retrieve a certain column, not all.
I make my request in java with BoolQUEryBuilder which gives:
BoolQueryBuilder query = boolQuery();
query.must(wildcardQuery('value', value + "*"));
return findAll(query);
The method findAll :
protected List<T> findAll(final BoolQueryBuilder query) {
Query searchQuery = (new NativeSearchQueryBuilder()).withQuery(query).build();
SearchHits<T> searchHits = this.elasticsearchRestTemplate.search(searchQuery, this.getClazz(), this.elasticsearchRestTemplate.getIndexCoordinatesFor(this.getClazz()));
return (List)SearchHitSupport.unwrapSearchHits(searchHits);
}
I would like to add a filter on the columns. To illustrate in SQL this gives:
Select column_one, column_two from table;
Refer source filtering to fetch only few fields from Elasticsearch query results.
As explained in the same document example below code shows which fields to include and which to exclude.
String[] includeFields = new String[] {"title", "innerObject.*"};
String[] excludeFields = new String[] {"user"};
sourceBuilder.fetchSource(includeFields, excludeFields);
With Spring Data Elasticsearch, you should try this instead:
...
//include only specific fields
final SourceFilter sourceFilter = new FetchSourceFilter(new String[]{"column_one", "column_two"}, null);
// assemble the query
Query searchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
searchQuery.addSourceFilter(sourceFilter);
...

Get affected rows after Mongo update

How can I instruct Mongo to return the affected rows after doing an update?
Currently it returns
{ "serverUsed" : "localhost:27017" , "ok" : 1 , "n" : 12 , "updatedExisting" : true}
which means 12 records was updated, but I want to find out which records they were.
One workaround is to do two queries, first to find the _id's, and second to actually update them but this is not good enough.
Many thanks
R.
Use the findAndModify() API. For example, following the guideline from this blog post MongoDB findAndModify() examples using Mongo Shell and Java Driver, you can write your update query as:
// findAndModify operation. Update colour to blue for cars having speed < 45
DBObject query = new BasicDBObject("speed",
new BasicDBObject("$lt", 45));
DBObject update = new BasicDBObject();
update.put("$set", new BasicDBObject("color", "Blue"));
DBCursor cursor = coll.find();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
coll.findAndModify(query, update);

MongoDB: Simple query issue

currently I'm trying to learn dealing with MongoDB in Java. I created the collection "plots" and inserted a document:
final Document plotObj = new Document();
plotObj.put(DataKey.PLOT_UUID.getKey(), plot.getUniqueId());
plotObj.put(DataKey.REGION_ID.getKey(), plot.getRegionId());
plotObj.put(DataKey.REGION_WORLD.getKey(), plot.getRegionWorld());
plotObj.put(DataKey.REGION_OWNER.getKey(), plot.getPlotOwner().isPresent() ? plot.getPlotOwner() : null);
plotObj.put(DataKey.PLOT_TRUSTED.getKey(), new BasicDBList().addAll(plot.getTrusted()));
this.collection.insertOne(plotObj);
"DataKey.PLOT_UUID.getKey()" represents a String. "plot.getUniqueId()" represents a java.util.UUID. After inserting this Document, I want to query it:
public boolean hasPlot(UUID plotId){
final BasicDBObject query = new BasicDBObject(DataKey.PLOT_UUID.getKey(), new BasicDBObject("$eq", plotId));
return this.collection.find(query).iterator().hasNext();
}
However this methods always returns false event though the Document was successfully inserted.
Maybe this problem can be fixed with ease but nevertheless: thanks in advance! :)
According to the documentation you don't need the $eq
just write
new BasicDBObject(DataKey.PLOT_UUID.getKey(), plotId));

MarkLogic - Sorting Query By Example Search

....
StringHandle rawHandle = new StringHandle(jsonString);
RawQueryByExampleDefinition querydef = queryManager.newRawQueryByExampleDefinition(rawHandle);
querydef.setCollections(collection);
StringHandle report = queryManager.validate(querydef, new StringHandle());
LOGGER.info("Query Def valididity: {}",report.toString());
StringHandle resultsHandle = new StringHandle().withFormat(Format.JSON);
queryManager.setPageLength(size);
queryManager.search(querydef, resultsHandle, startIndex);
....
I'm using the code above for MarkLogic search Query By Example, my question is how could you pass in a "sort by" criteria into the RawQueryByExampleDefinition to sort or order the resultset. For example I want the result to be sorted by emailAddress similar to the below query:
{
"$query":
{
"identifier":"user",
"$sort-by":"emailAddress"
}
}
How do I achieve the "sortby" as well as specifying desc or asc?
I think that would be done using a "combined query" from https://docs.marklogic.com/guide/java/searches#id_76144 with the sort-order option from https://docs.marklogic.com/search:search

Java MongoDB getting value for sub document

I am trying to get the value of a key from a sub-document and I can't seem to figure out how to use the BasicDBObject.get() function since the key is embedded two levels deep. Here is the structure of the document
File {
name: file_1
report: {
name: report_1,
group: RnD
}
}
Basically a file has multiple reports and I need to retrieve the names of all reports in a given file. I am able to do BasicDBObject.get("name") and I can get the value "file_1", but how do I do something like this BasicDBObject.get("report.name")? I tried that but it did not work.
You should first get the "report" object and then access its contents.You can see the sample code in the below.
DBCursor cur = coll.find();
for (DBObject doc : cur) {
String fileName = (String) doc.get("name");
System.out.println(fileName);
DBObject report = (BasicDBObject) doc.get("report");
String reportName = (String) report.get("name");
System.out.println(reportName);
}
I found a second way of doing it, on another post (didnt save the link otherwise I would have included that).
(BasicDBObject)(query.get("report")).getString("name")
where query = (BasicDBObject) cursor.next()
You can also use queries, as in the case of MongoTemplate and so on...
Query query = new Query(Criteria.where("report.name").is("some value"));
You can try this, this worked for me
BasicDBObject query = new BasicDBObject("report.name", "some value");

Categories