当前位置: 代码迷 >> java >> 返回嵌套在mongo文档中的随机元素
  详细解决方案

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

热度:41   发布时间:2023-07-17 20:21:49.0

我在Mongo数据库中有以下json文档。 show元素将具有几个season元素,也将具有几个Episodes元素,而转而又具有多个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元素等于我的字符串,则返回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: <positive integer> }

所以就你而言

{ $limit: 10 }

  相关解决方案