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?
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 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));
}
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<>());