java - 返回嵌套在 mongo 文档中的随机元素

标签 java json mongodb

我在 Mongo db 中有以下 json 文档。 show 元素将包含多个季节元素,其中还将包含多个剧集元素,而剧集元素又包含多个 QuestionEntry 元素。

 {
"show":[
{
 "season":[
    {
       "episodes":[
          {
             "questionEntry":{
                "id":1,
                "info":{
                   "seasonNumber":1,
                   "episodeNumber":5,
                   "episodeName":"A Hero Sits Next Door"
                },
                "questionItem":{
                   "theQuestion":"What is the name of the ringer hired by Mr. Weed?",
                   "attachedElement":{
                      "type":1,
                      "value":""
                   }
                },
                "options":[
                   {
                      "type":1,
                      "value":"Johnson"
                   },
                   {
                      "type":1,
                      "value":"Hideo"
                   },
                   {
                      "type":1,
                      "value":"Guillermo"
                   }
                ],
                "answer":{
                   "questionId":1,
                   "answer":3
                },
                "metaTags":[
                   "Season 1",
                   "Episode 5",
                   "Trivia",
                   "Arya Stark",
                   "House Stark"
                ]
             }
          }
       ]
    }
 ]
}
]
}

我已经能够返回问题元素,其中问题元素元标记条目等于我的搜索。例如。如果metaTag元素等于我的字符串,则返回metaTag元素所在的questionEntry元素,并搜索整个show元素并使用以下代码返回所有匹配项: (感谢 Yathish Manjunath 对这段代码的帮助)

 private DB mongoDatabase;
 private DBCollection mongoColl;
 private DBObject dbObject;

 // Singleton class
 // Create client (server address(host,port), credential, options)
    mongoClient = new MongoClient(new ServerAddress(host, port), 
            Collections.singletonList(credential),
            options);

 mongoDatabase = ClientSingleton.getInstance().getClient().getDB("MyDB");
 queryMetaTags("Season 1");

     //@SuppressWarnings("deprecation")
public void queryMetaTags(String query)
{            
    List<String> continentList = Arrays.asList(new String[]{query});
    DBObject matchFields = new 
       BasicDBObject("show.season.questions.questionEntry.metaTags", 
      new BasicDBObject("$in", continentList));
    DBObject groupFields = new BasicDBObject( "_id",
       "$_id").append("questions", 
       new BasicDBObject("$push","$show.season.questions"));
    //System.out.println("2");
    DBObject unwindshow = new BasicDBObject("$unwind","$show");
    DBObject unwindsea = new BasicDBObject("$unwind", "$show.season");
    DBObject unwindepi = new BasicDBObject("$unwind", 
      "$show.season.questions");
    DBObject match = new BasicDBObject("$match", matchFields);
    DBObject group = new BasicDBObject("$group", groupFields);  
    @SuppressWarnings("deprecation")
    AggregationOutput output = 
    mongoColl.aggregate(unwindshow,unwindsea,unwindepi,match,group);
    String s = JSON.serialize(dbObject);
    JSONObject json = null;

    for (DBObject result : output.results()) 
    {
        System.out.println(result);
        // pretty view for testing
        try 
        {
             json = new JSONObject(result);
             System.out.println(json.toString(4));
        } 
        catch (JSONException e1) 
        {
            e1.printStackTrace();
        }
    }
    System.out.println("In end of queryMetaTags");
}

我想像上面那样搜索,但只返回 10 个随机匹配的 QuestionEntry 元素?实现这一目标的最佳且最有效的方法是什么?

我不得不说我对任何数据库的搜索查询都是新手,只是不知道如何实现一个灵活的解决方案?希望这里有人可以提供帮助。

最佳答案

您可以使用$limit在聚合链中。请注意,您必须将其添加为最后一个链。

{ $limit: <positive integer> }

所以就你而言,

{ $limit: 10 }

关于java - 返回嵌套在 mongo 文档中的随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31639567/

相关文章:

java - Webdriver 是否使用 RPC 调用。 webdriver如何控制浏览器?

Javascript,没有时区的 Date.parse

python - CSV 到嵌套(分层)JSON - 使用 Python 标记父项

node.js - 基于 Mongoose 的应用架构

javascript - 如何在 Javascript 中添加 JSON 属性?

node.js - 如何计算一周总小时数?

java - 如何使用jpa从数据库中获取特定的id?

Java游戏无法读取图像文件

java - 使用 -source 7 或更高版本

c# - NancyFX如何处理序列化的DateTime?