Use Scala to manipulate MongoDB

Source: Internet
Author: User
Tags install mongodb mongoclient

Introduced

Scala is a functional object- oriented language that incorporates many unprecedented features while running on top of the JVM . As developers become more interested in Scala , and more and more tools are available, the Scala language will undoubtedly be an essential tool in your hands .

MongoDB is a product between a relational database and a non-relational database, the most versatile of the non-relational databases, most like relational databases. The data structure he supports is very loose and is a json - like bson format, so you can store more complex data types. Mongo 's biggest feature is that the query language he supports is very powerful, and its syntax is a bit like an object-oriented query language that almost implements most of the functionality of a relational database single-table query, and also supports indexing of data .

in this article, we'll show you how to use Scala how language and Mongodb for connection and data processing.

Environment Installation and configuration

First, to install MongoDB and Scala, if it is already installed, you can skip this step. Please search by yourself for specific installation steps.

Second, installing SBT,SBT is the build tool in Scala that works like Maven. Installation is relatively simple, the specific steps please refer to: http://www.scala-sbt.org/0.13/tutorial/zh-cn/Setup.html

Third, after the installation is complete, execute the SBT command on the console and a message similar to the following appears:

[Email protected] scala-project]# SBT

[INFO] Loading Global Plugins From/root/.sbt/0.13/plugins

[INFO] Set current project to Casbah Tutorial (in buildfile:/home/apache/src/scala-project/)

>

IV: Create a test project and load the Casbah library, Casbah is MongoDB Scala driver

mkdir Test-project

CD Test-project

VI BUILD.SBT, Input:

Name: = "Casbah Test"

Version: = "1.0"

Scalaversion: = "2.11.2"

Librarydependencies + = "Org.mongodb" percent "Casbah"% "2.7.3"

Note: Each line in the BUILD.SBT file should have a blank line split.

If you have any questions, please refer to http://mongodb.github.io/casbah/guide/installation.html

After completion of the input command: Sbtconsole, the first run will automatically download Casbah and other dependent libraries, after the completion of the load is similar to the following information.

Welcome to Scala version 2.11.2 (Java HotSpot (TM) 64-bit Server Vm,java 1.7.0_13).

Type in expressions to has them evaluated.

Type:help for more information.

Scala>

Connect to MongoDB

Loading Scala SHELL:SBT Console

Importcom.mongodb.casbah.imports._

Val mongoclient= mongoclient ("localhost", 27017)

Note: You can enter mongoclient in the console. + SPACEBAR, the system will automatically prompt for available actions.

Multiple connection modes are supported:

1. Simple Way

Connect to Default-localhost, 27017

Val mongoclient = Mongoclient ()

Connect to "MONGODB01" host, default port

Val mongoclient = mongoclient ("Mongodb01")

Connect to "MONGODB02" host, Port 42017

Val mongoclient = mongoclient ("mongodb02", 42017)

2. Uri method

Val uri = Mongoclienturi ("mongodb://localhost:27017/")

Val mongoclient = mongoclient (URI)

3. Support Authorization method

Challenge Response

Valserver = new ServerAddress ("localhost", 27017)

Valcredentials = Mongocredential.createmongocrcredential (UserName, Database,password)

Valmongoclient = mongoclient (server, List (credentials))

X.509protocol

Valserver = new ServerAddress ("localhost", 27017)

Valcredentials = mongocredential.createmongox509credential (userName)

Valmongoclient = mongoclient (server, List (credentials))

...

For more information about the connection, please refer to: http://mongodb.github.io/casbah/guide/connecting.html

We create a test_db database and test collection in MongoDB and choose a simple user password, as follows:

Val Server = newserveraddress ("localhost", 27017)

Val Credentials =mongocredential.createmongocrcredential ("User", "test_db", "Pass". ToArray)

Val mongoclient= mongoclient (server, List (credentials))

A connection is successful with a message similar to the following:

res2:com.mongodb.casbah.MongoClient = [email protected]

Get databases and connections:

Val db = Mongoclient ("test_db")

Db.collectionnames

Val coll = db ("Test")

Adding and removing changes and checking operation

Increase

Val user1 = mongodbobject ("name", "user1")

Val user2 = mongodbobject ("name", "User2")

Coll.insert (User1)

Coll.insert (User2)

Read

Coll.count ()//Read total number of records

You can also use Find to read records, such as reading all records and printing them:

Coll.find (). foreach (println)

Val query1 =mongodbobject ("name", "user1")

Coll.findone (Query1)

Update

Val update1 =mongodbobject ("email", "[email protected]")

Val result1 = coll.update (query1,update1)

println ("number updated:" +RESULT.GETN)

or Val result = coll.update (query, update, upsert=true)//upsert=true, if it does not exist, insert

Delete

Val Query2 = mongodbobject ("name", "User2")

Val result2 = Coll.remove (Query2)

Delete Collection

Coll.drop ()

For more information, refer to the user documentation for Casbah http://mongodb.github.io/casbah/index.html

Use Scala to manipulate MongoDB

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.