-2

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?

enter image description here

chridam
  • 100,957
  • 23
  • 236
  • 235
Alon Galpe
  • 55
  • 3
  • 10
  • 4
    did you try anything that will help us to see where you're stuck ? – s7vr Jan 14 '17 at 15:21
  • 1
    Also images as code are really discouraged here on StackOverlow, please update your question with the actual code, not images. – chridam Jan 14 '17 at 15:21
  • Possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – OneCricketeer Jan 14 '17 at 15:24

3 Answers3

0

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");
}
Jayanth
  • 5,954
  • 3
  • 21
  • 38
0

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));
}
chridam
  • 100,957
  • 23
  • 236
  • 235
0

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<>());
s7vr
  • 73,656
  • 11
  • 106
  • 127