从jsons数组中获取json字段

时间:2017-01-14 15:12:38

标签: java json mongodb mongodb-query

我有以下json文档。我想只检索所有的名字。给定一个电影名称,我需要返回所有用户名。

我正在使用Java,如果你也可以帮助我使用Java,那将是非常棒的。我怎么能这样做?

enter image description here

3 个答案:

答案 0 :(得分:0)

org.json图书馆

样本

//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");
}

答案 1 :(得分:0)

您可以对查询使用 distinct() 功能,如下所示:

mongo shell:

var results = db.movieToUsers.distinct("user.name", { "movieName": "Green Mile" });
printjson(results);

在Java中,这是通过 distinct() 方法实现的,例如

// 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));
}

答案 2 :(得分:0)

如果你使用的是Mongo 3.x驱动程序,你可以使用它。

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