在Mongo中使用游标迭代多个文档

时间:2017-10-12 07:59:48

标签: java mongodb

使用Java代码在mongo数据库中迭代文档时遇到问题。我在User_ID值的基础上迭代记录为" demo"在集合中。迭代时,它存储最新的记录而不是所有匹配的数据。代码如下:

public BasicDBObject Demo1(String User_ID) throws Exception {
        DB db = ConnectToDB.getConnection();
        DBCollection collection = db.getCollection("demo");
        BasicDBObject document = new BasicDBObject();
        BasicDBObject Project_Detail = new BasicDBObject();
        document.put("User_ID", User_ID);
        field.put("ProjectName", 1);
        field.put("ProjectNumber", 1);
        field.put("_id", 0);
        DBCursor cursor = collection.find(document, field);
while (cursor.hasNext()) {
                    BasicDBObject object=new BasicDBObject();
                    object = (BasicDBObject) cursor.next();

                    Project_Detail.append("ProjectName", object.get("ProjectName"));
                    Project_Detail.append("ProjectNumber", object.get("ProjectNumber"));
                    System.out.println("Project_Detail value is:" + Project_Detail);

                }
return Project_Detail;
}

我的mongo集合如下,它有两个文件:

{
    "_id" : ObjectId("59dc85905f0446bfb39417f5"),
    "User_ID" : "demo",
    "ProjectNumber" : "1",
    "ProjectName" : "Project1",
 },
{
    "_id" : ObjectId("59dc85a15f0446bfb39417f9"),
    "User_ID" : "demo",
    "ProjectNumber" : "2",
    "ProjectName" : "Project2",
 }

当我运行上面的代码时,它显示给定User_ID的以下结果:" demo":

 {
    "ProjectName": "Project2",
    "ProjectNumber": "2"}

但理想的结果应该是:

{
    "ProjectName": "Project1",
    "ProjectNumber": "1"},
{
    "ProjectName": "Project2",
    "ProjectNumber": "2"}

似乎它正在更新第二个计数器中的记录,因此在第二次迭代中更新第二个文档中的值。请指定如果我可以获取匹配的记录并将其存储在结果中。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

在第二次迭代中,您将替换相同键的值。这就是为什么结果中只剩下一个值的原因。 您应该使用BasicDBList来存储多个BasicDBObject

E.g

BasicDBList Project_Detail = new BasicDBList();
while (cursor.hasNext()) {
                    BasicDBObject object=new BasicDBObject();
                    object = (BasicDBObject) cursor.next();
                    BasicDBObject temp = new BasicDBObject();
                    temp.append("ProjectName", object.get("ProjectName"));
                    temp.append("ProjectNumber", object.get("ProjectNumber"));
                    Project_Detail.add(temp);

                }

BasicDBList转换为BasicDBObject

    BasicDBObject result = new BasicDBObject();
    result.putAll(Project_Detail.toMap());