I using a MongoCollection as following code :
MongoDatabase conn = getMongoConnection(DbName);
MongoCollection collection = conn.getConnection(CollectionName);
List<BasicDBObject> query = new ArrayList();
if (searchKey.containsKey("filter1")) {
String filter1= (String) searchKey.get("filter1");
query.add(new BasicDBObject("filter1", filter1));
}
if (searchKey.containsKey("filter2")) {
String filter2= (String) searchKey.get("filter2");
query.add(new BasicDBObject("filter2", filter2));
}
int rowAmount = (int) collection.count(new BasicDBObject("$and", query));
rowAmount gets the correct amount of data, but I want to know an actual query when it got the result. Any ideas how?
You can see actual queries sent to the server via command monitoring.
Related
I have list of attributes in mongo and I am querying some nested field. Here is my code,
public List<Brand> searchBrands(Request request) {
final MongoCollection<Document> collection = mongoDatabase.getCollection("shop");
final Document query = new Document();
final Document projection = new Document();
final List<Brand> brandList = new ArrayList<>();
query.append("_id", request.getId());
query.append("isActive", true);
if (request.Year() != null) {
query.append("attributes.name", "myYear");
query.append("attributes.value", request.getYear());
}
projection.append("brand.code", 1.0);
projection.append("brand.description", 1.0);
projection.append("_id", 0.0);
Block<Document> processBlock = document -> brandList.
add(Brand.builder().code(document.get("brand",Document.class).getString("code"))
.description(document.get("brand",Document.class).getString("description"))
.build());
collection.find(query).projection(projection).forEach(processBlock);
return brandList;}
Above code return results correctly, 72 item with same brand.code. But I want to fetch distinct according to brand.code How can I do that?
I'm not sure which mongodb client library you're using to create queries for mongodb;
I'm sharing the query that you can run in mongodb console to get the results you want. I hope you know how to create this query using your mongodb client library
db.shop.distinct('brand.code', myQuery)
//Replace myQuery with your query e.g. {isActive: true}
db.collection.find().forEach(function(element){
element.BOOKING_CREATED_DATE = ISODate(element.BOOKING_CREATED_DATE);
db.collection.save(element);
})
Please help to convert this query to DBobject type to run in spring boot
Finally found the answer
MongoClient mongo = new MongoClient();
DB db = mongo.getDB("datarepo");
DBCollection collection = db.getCollection("rawdata");
db.eval("db.rawdata.find( { BOOKING_CREATED_DATE : { $type : 2 } } ).forEach(function(element){" +
"element.BOOKING_CREATED_DATE = ISODate(element.BOOKING_CREATED_DATE);" +
"db.rawdata.save(element);})")
I have the following json document. I want to retrieve only all the names. Given a movie name I need to return all the user names.
I am using Java, if you can also assist me in Java it will be awesome. How can I do this?
You can use something like if you're using Mongo 3.x driver.
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection<Document> movieToUsers = db.getCollection("movieToUsers");
Bson filter = Filters.eq("movieName", "Green Mile");
List<String> names = movieToUsers.distinct("user.name", filter, String.class).into(new ArrayList<>());
You org.json library
sample
//Json object
JSONObject obj = new JSONObject(" .... ");
String id = obj.getString("_id");
String movieName = obj.getString("movieName");
//Json array
JSONArray users = obj.getJSONArray("user");
for (int i = 0; i < arr.length(); i++)
{
String name = user.getJSONObject(i).getString("name");
String name = user.getJSONObject(i).getString("date");
}
You can use distinct() function with a query as follows:
mongo shell:
var results = db.movieToUsers.distinct("user.name", { "movieName": "Green Mile" });
printjson(results);
In Java, this is implemented by the distinct() method, for example
// Get a new connection to the db assuming that it is running
MongoClient m1 = new MongoClient();
// use test as a database or use your own database
DB db = m1.getDB("test");
// fetch the collection object
DBCollection coll = db.getCollection("movieToUsers");
// call distinct method with the query and store results in variable results
List results = coll.distinct("speed", new BasicDBObject("movieName", "Green Mile"));
// iterate through the results list and print the names
for(int i=0;i<results.size();i++){
System.out.println(results.get(i));
}
I am trying to do fetch the data from database using ScrollableResults. Part of my code is below :
List list = null;
ScrollableResults items = null;
String sql = " from " + topBO.getClass().getName(); // topBO is my parent class so i pass the any of my child class name .
StringBuffer sqlQuery = new StringBuffer(sql);
Query query = sessionFactory.getCurrentSession().createQuery(sqlQuery.toString());
items = query.scroll();
int i = 0;
TopBO topBO;
while(items.next())
{
topBO= (TopBO) items.get()[i];
list.add(TopBO2); // got the exception at this line.
i++;
topBO= null;
}
items.close();
If i run the above code i am getting runtime error like java.lang.NullPointerException
You are trying to add the value in list which is not initialize.
It may helps you :
List list = new ArrayList();
replace with
List list = null;
I think topBO= (TopBO) items.get()[i]; is causing the problem.
I would suggest that you use result set transformer of query something like this
Query query = sessionFactory.getCurrentSession().createQuery(sqlQuery.toString());
list=query.setResultTransformer(Transformers.aliasToBean(YourClassName.class)).list();
I am using a Java driver to run some mongo text searches.
An example of my previous code is (where values is a String passed in):
DBCollection coll = db.getCollection("testCollection");
//create the basic object
DBObject searchCmd = new BasicDBObject();
//create the search cmd
searchCmd.put("text", "testCollection"); // the name of the collection (string)
// define the search word
searchCmd.put("search", value); // the term to search for (string)
// define the return values
searchCmd.put("project", new BasicDBObject("score", 1).append("name", 1).append("path", 0).append("_id", 0));
// get the results
BasicDBObject commandResult = db.command(searchCmd);
// Just out the results key
BasicDBList results = (BasicDBList) commandResult.get("results");
then I loop over the "results" and I get for each it score by
// Get the number ii
BasicDBObject element = (BasicDBObject) results.get(ii);
// Now get the score
double score = (double) element.get("score");
I want to upgrade to use find since that seems the way 2.6 and later prefers it. So far I have:
DBCollection coll = db.getCollection("testCollection");
BasicDBObject query = new BasicDBObject();
query.append("$text", new BasicDBObject("$search", value));
DBCursor cursor = coll.find(query);
However, I am not sure how to get the score.
I tried doing something like:
query.append("score", new BasicDBObject("$meta", "textScore"));
But this does not work. I would like to be able to get the name and the score so that I can then insert them into a new collection that will also hold the score.
I can get the name easily by:
while (cursor.hasNext())
{
DBObject next = cursor.next();
String name = next.get("name").toString();
}
But how do I get the score?
I found this interesting page: http://api.mongodb.org/java/current/
it appears that find can take a second DBObject which has the fields.
I created a new object:
BasicDBObject fields = new BasicDBObject();
fields.append("score", new BasicDBObject("$meta", "textScore"));
and I am calling find using:
DBCursor cursor = coll.find(query, fields);
and now I can get the score the same way I can get the name.