我是MongoDB的新手,我将它与Java驱动程序一起使用。我有这个文档结构:
{
"_id" : ObjectId("5598734f96de4e47f61f250c"),
"restaurant_name" : ["restaurant_1"],
"menu" : [
"A",
"B",
"C",
"D",
"E",
"F"
]
}
根据这个例子,我想把菜单的所有元素放在一个数组中(用数组的元素做一些事情)并显示它们:
Name: restaurant_1
Menu: A B C D E F
我想对数组的元素做些什么。
答案 0 :(得分:0)
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
public class QueryDB {
static MongoClient clientMongo;
public static void main(String arg[]) {
getMenu("restaurant_1");
}
private static void getMenu(String restaurant) {
// TODO Auto-generated method stub
try {
clientMongo = new MongoClient();
DB db = clientMongo.getDB("**DATABASE NAME**");
DBCollection collectionMongo = db.getCollection("**COLLECTION NAME**");
DBCursor cursor = collectionMongo.find(new BasicDBObject("menu",
restaurant));
if (cursor.count() == 0)
System.out.println("No Menu found");
while (cursor.hasNext()) {
System.out.println(cursor.next().get("menu"));
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("Could not connect to Database");
e.printStackTrace();
}
}
}