简体   繁体   中英

Is there something I am missing with my aggregate and find code?

So I have a working Python code for mongoDB, and for a class I am in right now, I am trying to put this code into Java. At the moment I have everything working correctly besides my aggregate portion, and a find command that is supposed to yield multiple results.

I have done some research which showed me it had to be in a loop for it to print out right, but I am getting same error. Also I found some stuff about maybe it being a cursor that is timing out possibly, it is a pretty big file I am working with, but some of the results for that are not working such as the .noCursorTimeout(true).

Here is my set up for the aggregate:

public class Aggregate {

    public static Object AggregateDocument(String input) {

        //Get mongo set up
        @SuppressWarnings("resource")
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase database = mongoClient.getDatabase("market");
        MongoCollection<Document> collection = database.getCollection("stocks");

        //Get the documents set up for each section of the aggregate command
        //Set up the Match
        Document match = new Document("$match", new Document("Sector", input));
        //Set up the Project
        Document project1 = new Document("_id", 1);
        Document project2 = project1.append("Shares Outstanding", 1);
        Document project3 = project2.append("Industry", 1);
        Document project4 = project3.append("Sector", 1);
        Document project = new Document("$project", project4);
        //Set up the Group
        Document group1 = new Document("_id", "$Industry");
        Document group2 = group1.append("Total Outstanding Shares", new Document("$sum", "$Shares Outstanding"));
        Document group = new Document("$group", group2);

        //Call the aggregate command
        AggregateIterable<Document> agg = collection.aggregate(Arrays.asList(match, project, group));

        //Print out the result
        for (Document printAggs : agg)
        {
            System.out.println(printAggs);
        }

        return agg;
    }
}

Here is my code for my Find command

public class FindStr {

    public static Object FindString(String input) {

        //Get mongo set up
        @SuppressWarnings("resource")
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase database = mongoClient.getDatabase("market");
        MongoCollection<Document> collection = database.getCollection("stocks");

        //Get the documents set up 
        Document doc1 = new Document("Industry", input);
        Document doc2 = new Document("Ticker", 1);

        //Set up the find() command
        MongoCursor<Document> cursor = collection.find(doc1).projection(doc2).noCursorTimeout(true).iterator();

        //Print out the results
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }


        return cursor;
    }

}

For the aggregate command I am supposed to get a list of documents that fit that aggregate, and pretty much the same for the find string command. What I am getting is similar results to each other, for example here is what I am getting for the find string output:

Enter in a string to search for (enter it in quotes), or b to go back: 
"Medical Laboratories & Research"
Mar 30, 2019 5:52:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Mar 30, 2019 5:52:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Mar 30, 2019 5:52:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:3, serverValue:74}] to localhost:27017
Mar 30, 2019 5:52:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 6]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, roundTripTimeNanos=477995}
Mar 30, 2019 5:52:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:4, serverValue:75}] to localhost:27017

So I am posting my own answer because apparently the code is working fine. My inputs were wrong, with how I learned to set it up for MongoDB, I had it set up looking for an input, and usually the format for json stuff is {"key":"value"}, so when I was imputing the value part, I wanted it to be in quotes for it. But apparently if you do not put it in quotes, it works perfectly fine as intended. I have it working fine in Python so I have a working example to look at. Also, those 1's in the project portion would not work until I took them back out of string format and into integer format, those 1's really mean "true", for it to project just those keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM