如何使用java代码根据building_Id和floor_Id从MongoDB获取数据?
例如:如果我发送building_Id = 3 & Floor_Id = 23。我只需要基于building_Id = 3 & Floor_Id = 23 的特定数据列表。
这是 MongoDB 中的示例数据
{
"_id" : ObjectId("5a685c9bf35e8155da228460"),
"building_Id" : "3",
"floor_Id" : "23",
"x" : "363.0876770019531",
"y" : "430.05975341796875"
}
{
"_id" : ObjectId("5a685c9cf35e8155da228462"),
"building_Id" : "3",
"floor_Id" : "23",
"x" : "367.85260009765625",
"y" : "429.10675048828125"
}
{
"_id" : ObjectId("5a685c9cf35e8155da228464"),
"building_Id" : "2",
"floor_Id" : "22",
"x" : "375.47650146484375",
"y" : "429.10675048828125"
}
{
"_id" : ObjectId("5a685c9cf35e8155da228466"),
"building_Id" : "2",
"floor_Id" : "22",
"x" : "387.8653259277344",
"y" : "429.10675048828125"
}
这是我从 MongoDb 获取数据的 Java 代码,但我正在从 MongoDb 获取所有数据
try {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("trackbitDB");
DBCollection col = db.getCollection("objects_path");
BasicDBObject doc = new BasicDBObject();
// Selecting Records from MongoDB
col.insert(doc);
System.out.println("Collection has selected successfully");
DBCursor cursor = col.find();
int index = 1;
while (cursor.hasNext()) {
System.out.println("Inserted Document: " + index);
System.out.println(cursor.next());
index++;
}
} catch(Exception e) {
e.printStackTrace();
}
最佳答案
//Build the query
BasicDBObject query = new BasicDBObject("building_Id", "3").append("floor_Id", "23");
//Provide the query as an argumnt to the find()
DBCursor cursor = col.find(query);
//Iterate the cursor
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
关于java - 如何使用java代码根据building_Id和floor_Id从MongoDB获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48435406/