Collecting document fields to an array from Mongo DB in ScalaIs the Scala 2.8 collections library a case of “the longest suicide note in history”?Add new field to every document in a MongoDB collectionQuery for documents where array size is greater than 1How to list all collections in the mongo shell?Filter documents in collection A using information from a collection B - how?How append new Document in complicated Collection-ObjectWhat datatype is returned by MongoCollection.find()?MongoDuplicateKeyExceptionUpdate MongoDB collection with values from an arrayHow to get total number of array elements for a particular field in a MongoDB collection?

Employers keep telling me my college isn't good enough - is there any way to fix this?

How do we handle pauses in a dialogue?

Has anyone in space seen or photographed a simple laser pointer from Earth?

Is there any reason why MCU changed the Snap to Blip

What is a "shilicashe?"

How can a dictatorship government be beneficial to a dictator in a post-scarcity society?

How to befriend private nested class

Fast validation of time windows in a routing problem

Why would non-kinetic weapons be used for orbital bombardment?

Can I run a #12 outlet branch and a #14 light branch off a 30A breaker?

Should disabled buttons give feedback when clicked?

Single word for "refusing to move to next activity unless present one is completed."

Great Unsolved Problems in O.R

How do you move up one folder in Finder?

Would dual wielding daggers be a viable choice for a covert bodyguard?

Does Multiverse exist in MCU?

How would vampires avoid contracting diseases?

How can I get a player to accept that they should stop trying to pull stunts without thinking them through first?

What is this little owl-like bird?

Optimization terminology: "Exact" v. "Approximate"

Placing text inside a loop

For a hashing function like MD5, how similar can two plaintext strings be and still generate the same hash?

Why do we need common sense in AI?

What's the point of having a RAID 1 configuration over incremental backups to a secondary drive?



Collecting document fields to an array from Mongo DB in Scala


Is the Scala 2.8 collections library a case of “the longest suicide note in history”?Add new field to every document in a MongoDB collectionQuery for documents where array size is greater than 1How to list all collections in the mongo shell?Filter documents in collection A using information from a collection B - how?How append new Document in complicated Collection-ObjectWhat datatype is returned by MongoCollection.find()?MongoDuplicateKeyExceptionUpdate MongoDB collection with values from an arrayHow to get total number of array elements for a particular field in a MongoDB collection?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















So I have a collection of news articles scored by page views from Mongo DB that I query like this:



// To directly connect to the default server localhost on port 27017
val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
val database: MongoDatabase = mongoClient.getDatabase("Posts")
var collection: MongoCollection[Document] = database.getCollection("news")

collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>println(s"$doc.get("views")"))


This prints:



Some(BsonInt32value=66043)
Some(BsonInt32value=66306)
Some(BsonInt32value=66336)
Some(BsonInt32value=66365)
Some(BsonInt32value=66384)


So now I want to collect all of those values into an array, which I have tried to do via this line of code:



var scores = collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>doc.get("score").map(_.asInt32().getValue).collect())


But the .collect() does not work.



What is the best way to turn the Mongo field into an array of Ints?










share|improve this question




























    1















    So I have a collection of news articles scored by page views from Mongo DB that I query like this:



    // To directly connect to the default server localhost on port 27017
    val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
    val database: MongoDatabase = mongoClient.getDatabase("Posts")
    var collection: MongoCollection[Document] = database.getCollection("news")

    collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>println(s"$doc.get("views")"))


    This prints:



    Some(BsonInt32value=66043)
    Some(BsonInt32value=66306)
    Some(BsonInt32value=66336)
    Some(BsonInt32value=66365)
    Some(BsonInt32value=66384)


    So now I want to collect all of those values into an array, which I have tried to do via this line of code:



    var scores = collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>doc.get("score").map(_.asInt32().getValue).collect())


    But the .collect() does not work.



    What is the best way to turn the Mongo field into an array of Ints?










    share|improve this question
























      1












      1








      1


      1






      So I have a collection of news articles scored by page views from Mongo DB that I query like this:



      // To directly connect to the default server localhost on port 27017
      val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
      val database: MongoDatabase = mongoClient.getDatabase("Posts")
      var collection: MongoCollection[Document] = database.getCollection("news")

      collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>println(s"$doc.get("views")"))


      This prints:



      Some(BsonInt32value=66043)
      Some(BsonInt32value=66306)
      Some(BsonInt32value=66336)
      Some(BsonInt32value=66365)
      Some(BsonInt32value=66384)


      So now I want to collect all of those values into an array, which I have tried to do via this line of code:



      var scores = collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>doc.get("score").map(_.asInt32().getValue).collect())


      But the .collect() does not work.



      What is the best way to turn the Mongo field into an array of Ints?










      share|improve this question














      So I have a collection of news articles scored by page views from Mongo DB that I query like this:



      // To directly connect to the default server localhost on port 27017
      val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
      val database: MongoDatabase = mongoClient.getDatabase("Posts")
      var collection: MongoCollection[Document] = database.getCollection("news")

      collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>println(s"$doc.get("views")"))


      This prints:



      Some(BsonInt32value=66043)
      Some(BsonInt32value=66306)
      Some(BsonInt32value=66336)
      Some(BsonInt32value=66365)
      Some(BsonInt32value=66384)


      So now I want to collect all of those values into an array, which I have tried to do via this line of code:



      var scores = collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>doc.get("score").map(_.asInt32().getValue).collect())


      But the .collect() does not work.



      What is the best way to turn the Mongo field into an array of Ints?







      mongodb scala bson subscribe






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Feb 25 at 4:03









      EliSquaredEliSquared

      3866 silver badges18 bronze badges




      3866 silver badges18 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          0














          I figured out a solution, though I don't completely understand it:



          import org.mongodb.scala._
          import org.mongodb.scala.model.Filters._
          import org.mongodb.scala.model.Projections._

          object main extends App
          //Connect to Mongo Client and DB
          val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
          val database: MongoDatabase = mongoClient.getDatabase("MyDatabase")

          //Get Collection
          val collection: MongoCollection[Document] = database.getCollection("collectionName")

          //Returns the object with specified fields in projection
          //as a Future observable containing MongoDB Documents
          val collScores = collection.find(equal("id","id123")).limit(5).projection(fields(include("id", "score", "time"), excludeId()))

          //Maps the document fields to tuples and converts them
          //to non BSon values since they are easier to work with
          //than future observables.
          val listMapScores = collScores.map(doc=>(doc("id").asString.getValue,doc("score").asInt32.getValue,doc("time").asDouble.getValue)).collect().results().head




          I am not sure why you need to do both results() and then head in the last line. If you don't take the head you end up with a Seq[Seq(String,Int)]]. From what I can tell the future observable contains the same values regardless of if you take the head or the Nth term in the series.






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54859347%2fcollecting-document-fields-to-an-array-from-mongo-db-in-scala%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I figured out a solution, though I don't completely understand it:



            import org.mongodb.scala._
            import org.mongodb.scala.model.Filters._
            import org.mongodb.scala.model.Projections._

            object main extends App
            //Connect to Mongo Client and DB
            val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
            val database: MongoDatabase = mongoClient.getDatabase("MyDatabase")

            //Get Collection
            val collection: MongoCollection[Document] = database.getCollection("collectionName")

            //Returns the object with specified fields in projection
            //as a Future observable containing MongoDB Documents
            val collScores = collection.find(equal("id","id123")).limit(5).projection(fields(include("id", "score", "time"), excludeId()))

            //Maps the document fields to tuples and converts them
            //to non BSon values since they are easier to work with
            //than future observables.
            val listMapScores = collScores.map(doc=>(doc("id").asString.getValue,doc("score").asInt32.getValue,doc("time").asDouble.getValue)).collect().results().head




            I am not sure why you need to do both results() and then head in the last line. If you don't take the head you end up with a Seq[Seq(String,Int)]]. From what I can tell the future observable contains the same values regardless of if you take the head or the Nth term in the series.






            share|improve this answer





























              0














              I figured out a solution, though I don't completely understand it:



              import org.mongodb.scala._
              import org.mongodb.scala.model.Filters._
              import org.mongodb.scala.model.Projections._

              object main extends App
              //Connect to Mongo Client and DB
              val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
              val database: MongoDatabase = mongoClient.getDatabase("MyDatabase")

              //Get Collection
              val collection: MongoCollection[Document] = database.getCollection("collectionName")

              //Returns the object with specified fields in projection
              //as a Future observable containing MongoDB Documents
              val collScores = collection.find(equal("id","id123")).limit(5).projection(fields(include("id", "score", "time"), excludeId()))

              //Maps the document fields to tuples and converts them
              //to non BSon values since they are easier to work with
              //than future observables.
              val listMapScores = collScores.map(doc=>(doc("id").asString.getValue,doc("score").asInt32.getValue,doc("time").asDouble.getValue)).collect().results().head




              I am not sure why you need to do both results() and then head in the last line. If you don't take the head you end up with a Seq[Seq(String,Int)]]. From what I can tell the future observable contains the same values regardless of if you take the head or the Nth term in the series.






              share|improve this answer



























                0












                0








                0







                I figured out a solution, though I don't completely understand it:



                import org.mongodb.scala._
                import org.mongodb.scala.model.Filters._
                import org.mongodb.scala.model.Projections._

                object main extends App
                //Connect to Mongo Client and DB
                val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
                val database: MongoDatabase = mongoClient.getDatabase("MyDatabase")

                //Get Collection
                val collection: MongoCollection[Document] = database.getCollection("collectionName")

                //Returns the object with specified fields in projection
                //as a Future observable containing MongoDB Documents
                val collScores = collection.find(equal("id","id123")).limit(5).projection(fields(include("id", "score", "time"), excludeId()))

                //Maps the document fields to tuples and converts them
                //to non BSon values since they are easier to work with
                //than future observables.
                val listMapScores = collScores.map(doc=>(doc("id").asString.getValue,doc("score").asInt32.getValue,doc("time").asDouble.getValue)).collect().results().head




                I am not sure why you need to do both results() and then head in the last line. If you don't take the head you end up with a Seq[Seq(String,Int)]]. From what I can tell the future observable contains the same values regardless of if you take the head or the Nth term in the series.






                share|improve this answer















                I figured out a solution, though I don't completely understand it:



                import org.mongodb.scala._
                import org.mongodb.scala.model.Filters._
                import org.mongodb.scala.model.Projections._

                object main extends App
                //Connect to Mongo Client and DB
                val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
                val database: MongoDatabase = mongoClient.getDatabase("MyDatabase")

                //Get Collection
                val collection: MongoCollection[Document] = database.getCollection("collectionName")

                //Returns the object with specified fields in projection
                //as a Future observable containing MongoDB Documents
                val collScores = collection.find(equal("id","id123")).limit(5).projection(fields(include("id", "score", "time"), excludeId()))

                //Maps the document fields to tuples and converts them
                //to non BSon values since they are easier to work with
                //than future observables.
                val listMapScores = collScores.map(doc=>(doc("id").asString.getValue,doc("score").asInt32.getValue,doc("time").asDouble.getValue)).collect().results().head




                I am not sure why you need to do both results() and then head in the last line. If you don't take the head you end up with a Seq[Seq(String,Int)]]. From what I can tell the future observable contains the same values regardless of if you take the head or the Nth term in the series.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 26 at 1:34

























                answered Mar 1 at 3:25









                EliSquaredEliSquared

                3866 silver badges18 bronze badges




                3866 silver badges18 bronze badges
















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54859347%2fcollecting-document-fields-to-an-array-from-mongo-db-in-scala%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Obelisk of Theodosius Contents History Description Notes Bibliography Further reading External links Navigation menuAge of spirituality : late antique and early Christian art, third to seventh centuryOver 60 picturesObelisks of the World41°00′21.24″N 28°58′31.43″E / 41.0059000°N 28.9753972°E / 41.0059000; 28.97539727724550-7235741376235741376

                    밀양 대씨 역사 각주 함께 보기 둘러보기 메뉴밀양 대씨

                    1973년 목차 사건 문화 탄생 사망 노벨상 달력 둘러보기 메뉴