从2个集合中检索多个条目

时间:2014-03-28 06:59:17

标签: java json mongodb

情境:

我有两个JSON存储在以下格式的mongodb中:(他们来自Yelp Educational)

JSON1 :( Yelp Business)

   {
     "business_id":"tl9XIP5trlkcuSfTQqe5jg",
     "full_address":"632 N Estrella Pkwy\nGoodyear, AZ 85338",
     "hours":{
   },
   "open":true,
   "categories":[
   "Fast Food",
   "Restaurants"
   ],
   "city":"Goodyear",
   "review_count":6,
   "name":"McDonalds",
   "neighborhoods":[

   ],
   "longitude":-112.39319500000001,
   "state":"AZ",
   "stars":2.0,
   "latitude":33.453887000000002,
   "attributes":{
   "Take-out":true,
   "Wi-Fi":"free",
   "Drive-Thru":true,
   "Alcohol":"none",
   "Caters":false,
   "Noise Level":"average",
   "Takes Reservations":false,
   "Delivery":false,
   "Parking":{
     "garage":false,
     "street":false,
     "validated":false,
     "lot":false,
     "valet":false
  },
  "Has TV":true,
  "Outdoor Seating":false,
  "Attire":"casual",
  "Waiter Service":false,
  "Accepts Credit Cards":true,
  "Good for Kids":true,
  "Price Range":1
   },
   "type":"business"
}

JSON2 :(评论)

{
   "votes":{
   "funny":0,
   "useful":0,
   "cool":0
   },
   "user_id":"pNvoNTu6U7Ek2w_xe4QO-w",
   "review_id":"qyUlYgt68wexC_6qLL0sKg",
   "stars":1,
   "date":"2012-03-12",
   "text":"The worst McDonalds I've ever been to. The burgers are barely room temp and the cheese is barely melted on them even though they microwave them! Which is disgusting as it is. Chicken nuggets are always old and greasy (and again never hot enough). Filet o fish cold and gross..and either unmelted cheese or cheese that was nuked so long that it is like plastic. Nasty. I've never had a decent meal here. Haven't gone in months. Gross.",
   "type":"review",
   "business_id":"tl9XIP5trlkcuSfTQqe5jg"
}

他们都有相同的business_id

问题陈述:我如何编写查询以便我可以获取"类别":"快餐"并同时得到评论?

我能够检索一个但不能检索。请评论!

代码:

System.out.println("Fast Food Restaurants");

BasicDBObject rest = new BasicDBObject();
rest.put("categories", "Indian");
DBCursor cursor2 = table.find(rest);
while(cursor2.hasNext()){ //display all fast food restaurants
    System.out.println(cursor2.next());
}

如何显示其他JSON的评分?

谢谢你的时间!

1 个答案:

答案 0 :(得分:1)

你必须分两步完成。在Mongo,没有加入。因此,您无法编写单个查询来访问来自两个不同集合的数据。

您在以下步骤中获取了该商家 -

BasicDBObject rest = new BasicDBObject();
rest.put("categories", "Indian");

下一步 -

DBObject query = new BasicDBObject();
DBCursor cursor3 = null;
DBObject dbObject = null;
while(cursor2.hasNext()){ //display all fast food restaurants
    dbObject = cursor2.next();
    query.put("business_id",dbObject.get("business_id"))//get the business_id from dbObject returned from above
    cursor3 = table2.find(query); // here you have all the reviews for that business.
    //next loop through cursor3 for your reviews
}

在你的mongodb文件中,如果你将所有内容都存储为String,那么你可以使用dbObject.toString()获取json,然后使用gson的jackson转换为java pojo。