需要使用Java 3.12.0驱动程序从Java应用程序从mongoDB Atlas获取具有相同first_name的客户的customerID列表

通过使用以下代码,我可以获取具有相同first_name的客户对象的列表,但是对于我的下一个操作,我只需要所有提取的客户中的customerID s,相反,我只会得到第一个为所有对象提取了customerID。谁能帮忙吗?

MongoClienturi uri = new MongoClienturi("mongodb+srv://sumitraojha:<pwd>@cluster0-tkx83.mongodb.net/customer?retryWrites=true&w=majority");
MongoClient mongoClient = new MongoClient(uri);
System.out.println("The connection to mongoDB is established");

//MongoDB Customer Database connection
MongoDatabase cust_database = mongoClient.getDatabase("customer");
System.out.println("The connection to Database\t"+cust_database.getName()+"\tis established successfully");
//System.out.println("the database is "+cust_database.getName());

//Displaying the Queried Document
System.out.println("\n Enter the customer Name to search:\n ");
Scanner sc = new Scanner(System.in);
String fname = sc.next();
System.out.println("\n The Customer Details are:");
MongoCollection<Document> newcustDetails = cust_database.getcollection("NewCustomerDetails");

MongoCursor<Document> custcursor1 = newcustDetails.find(eq("first_name",fname)).iterator(); 
//System.out.println(custcursor1); 
ArrayList<String> value = new ArrayList<String>();
try { 
    while(custcursor1.hasnext()) 
    { 

    System.out.println("\n"+custcursor1.next().toJson());
    String temp = newcustDetails.find().projection(Projections.include("CustomerID")).first().getString("CustomerID");
    System.out.println(temp);
    value.add(temp);
    } 

    } 
    finally { 
              // TODO: handle finally clause
              custcursor1.close(); 
              }
System.out.println("\n The Customer ID are:\t\t");
    Iterator<String> i1=value.iterator();  
    while(i1.hasnext())  
    {  
        System.out.println(i1.next());  
    }  

this is the output i am getting

dongping303 回答:需要使用Java 3.12.0驱动程序从Java应用程序从mongoDB Atlas获取具有相同first_name的客户的customerID列表

我相信您在此行中使用查找查询时需要应用投影

MongoCursor<Document> custcursor1 = newcustDetails.find(eq("first_name",fname)).projection(Projections.include("CustomerID")).iterator(); 

因此,您不需要使用辅助查找查询。希望我能理解您的确切问题并回答您的问题。

个人,如果您需要逐步进行操作,我建议您使用“聚合管道”而不是“查找/投影”。

本文链接:https://www.f2er.com/2398637.html

大家都在问