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

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현