Scala's additions and deletions to MONGODB operations

Source: Internet
Author: User
Tags mongoclient mongodb driver

===========================================

Original link: Scala to MongoDB additions and deletions to the operation reproduced please specify the source!

===========================================

Environment dependent: jdk1.8, Scala 2.12, Idea

MongoDB driver:3.1.1. Note that the MONGO for Scala driver involves multiple jars (such as) and relies on Mongo-java-driver.jar

The SBT used here relies on management, adding dependencies directly to BUILD.SBT:librarydependencies + = "Org.mongodb" percent "Casbah"% " 3.1.1" (It is strongly recommended to use this method to add dependencies)

First, create a database connection

A: You do not need A username and password to get MongoDB directly.

  //   No permission authentication connection  def createdatabase (url:string, Port:int, dbname:string): MongoDB = {    mongoclient (URL, port). Getdb (DbName)  }

It is important to note that there are two mongoclient classes in the imported jar package, one from the mongo-java-driver.jar com. MongoDB. Mongoclient, another from the com.mongodb of Casbah-core_2.12:3.1.1.jar . Casbah. Mongoclient. The former is for Java calls, Scala uses the latter!!!

So when importing packages, be aware that: importcom.mongodb.casbah.MongoClient

B: Connect through permission verification

// Verify Connection Permissions  def createdatabase (url:string, Port:int, dbname:string, Loginname:string, password:string): MongoDB = {     New serveraddress (URL, port)     // Note: There are 6 ways to create connections in Mongocredential, which are connected using the MONGODB_CR mechanism. If you choose an error, permissions validation fails with    var credentials = mongocredential.createcredential (loginName, DbName, Password.tochararray)    = mongoclient (server, List (credentials))    Mongoclient.getdb (dbName)  }

It is important to note that mongocredential. createcredential (), there are six authentication mechanisms in mongocredential , which are created using createcredential(), and the use of errors will validate the failure

Com.mongodb.MongoSecurityException:Exception authenticating

caused By:com.mongodb.MongoCommandException:Command failed with error: ' Auth failed ' on server localhost:27017. The full response is {"OK": 0.0, "errmsg": "Auth Failed", "code": "codename": "Authenticationfailed"}

The method comments are as follows:

/**
* Creates a mongocredential instance with an unspecified mechanism. The client would negotiate the best mechanism
* Based on the version of the server, the client is authenticating to. If the server version is 2.8 or higher,
* The driver would authenticate using the scram-sha-1 mechanism. Otherwise, the driver would authenticate using the
* MONGODB_CR mechanism.
*
* @param userName the user name
* @param the database where the user is defined
* @param password The user ' s password
*/

Second, Data add

  Def testinsert (): Unit = {    for (i <-1 to )      collection. Insert ( Mongodbobject (new SimpleDateFormat ("Yyyy-mm-dd"). Parse ("2016-03-25"))  }

The collection here are created below:

Collection= CreateDatabase ("localhost", 27017, "MyTest", "User", "123456"). GetCollection ("user")

When the data is inserted, the collection is automatically created if it does not exist (this is user) and is automatically added if the document does not contain the "_id" field.

There is a Save method in dbcollection where the Save method differs from the insert in that when "_id" exists in the collection, save will update the data, and insert will not do anything

Select the appropriate data insertion function as needed

After storing the data are as follows:

{"_id": {"$oid": "592AD4BE45AEFD09F4867F1E"}, "name": "Jack86", "email": "[email protected]", "Age": 11, " BirthDay ": {" $date ":" 2016-03-24t16:00:00.000z "}}
{"_id": {"$oid": "592ad4be45aefd09f4867f1f"}, "name": "Jack87", "email": "[email protected]", "Age": 12, " BirthDay ": {" $date ":" 2016-03-24t16:00:00.000z "}}
{"_id": {"$oid": "592ad4be45aefd09f4867f20"}, "name": "Jack88", "email": "[email protected]", "Age": All, "b Irthday ": {" $date ":" 2016-03-24t16:00:00.000z "}}
{"_id": {"$oid": "592ad4be45aefd09f4867f21"}, "name": "Jack89", "email": "[email protected]", "age": +, "b Irthday ": {" $date ":" 2016-03-24t16:00:00.000z "}}

Third, Data Update modification

A: Update mode one

 def testupdate (): Unit = {var query  = mongodbobject ("name", "User1", " Email "," [email protected] ") var value  = Mongodbobject (" name "," use " R1 "," email "," [email protected] ") println (" ========= before update =========== = ") var query02  = mongodbobject (" name "," user1 " )  collection . Find (query02). ForEach (x  => println (x))  //  query: queries based on this condition    Value: Sets the first data of the query out result set to value    collection . Update (Query,value) println ( "=========" after the update ============ " collection . Find (QUERY02). ForEach (x  => println (x))}  

The results of the operation are as follows: ( note that only one record is updated here, not all data that matches the results are updated )

B: Update Mode II

Def testUpdate02 (): Unit ={var query= Mongodbobject ("name", "user1", "email", "[email protected]") var value=NewBasicdbobject ("$set",NewBasicdbobject ("Email", "[email protected]"))    //var value = Mongodbobject ("$set", Mongodbobject ("name", "user1", "email", "[email protected]" )println ("========= ============ before Update") var query02= Mongodbobject ("name", "user1") Collection.find (query02). ForEach (x=println (x)) collection.update (query, value,true,true) println ("============ after ========= update") Collection.find (query02). ForEach (x=println (x))}

Note the method:collection.update (query, value,true, true).

Third parameter: when true, inserts a document if no document matches the update Qu ery criteria

    The fourth parameter: When True, updates all documents in the collection. Match the update query criteria, otherwise on LY updatesOne "when this value is true, all result set data is updated, but only if value must be defined using the $XXX mode." The source code is as follows:

Four, the data query (recommended to see this article: MongoDB Learning Notes (query))

Def testselect (): Unit ={println ("========= Querying all Data ===================") Collection.find (). ForEach (x=println (x)) println ("========= Query name =" user1 "email=" [email protected] "===================") Collection.find (Mongodbobject ("Name", "user1", "email", "[email protected]"). Limit (3). ForEach (x =println (x))//Note that you cannot use put to add additional query criteria, because put returns HASHMAP, where you should use append to add a query condition//var query = new Basicdbobject ("name", New Basicdbobject ("$in", ("user145", "user155")). Put ("qty", New Basicdbobject  ("$in", (25.0,105.0))) The method error//query conditions are: (Name in ("user145", "user155")) && (qty in (25.0,105.0) )println ("========= Query (name in (\" User145\ ", \" User155\ ")) && (qty in (25.0,105.0)) ===================") var query=NewBasicdbobject ("Name",NewBasicdbobject ("$in", ("user145", "user155"))). Append ("Qty",NewBasicdbobject ("$in", (25.0, 105.0)) collection.find (query). ForEach (x=println (x)) println ("========= query start >= && end<= 80 Data ===================") var query02=NewBasicdbobject ("Start",NewBasicdbobject ("$gte",)). Append ("End",NewBasicdbobject ("$lte", 80) ) Collection.find (query02). ForEach (x=println (x))}

The query results are as follows:

V. Deletion of data

Data deletion is primarily a query condition that deletes all data that meets the criteria.

  Def testdelete (): Unit ={    = mongodbobject ("name", "user1", "email", "[email protected]")    println ("========= before deletion ============")    = println (x))    //  This parameter is just a query condition and all collections that match that condition will be deleted. The point is how to build the query    collection.remove (query)    println ("========= before deleting ============")     = println (x))  }

The results of the implementation are as follows:

========= before deleting ============

{"_id": {"$oid": "592a0c8345aefd1d404c3ed9"}, "name": "user1", "email": "[email protected]"}
{"_id": {"$oid": "592a0c8345aefd1d404c3eda"}, "name": "user1", "email": "[email protected]"}
{"_id": {"$oid": "592a0c9845aefd0dfc2a1e21"}, "name": "user1", "email": "[email protected]"}
{"_id": {"$oid": "592a0c9845aefd0dfc2a1e23"}, "name": "user1", "email": "[email protected]"}
{"_id": {"$oid": "592a740f434a43d3b1529d0e"}, "name": "user1", "email": "[email protected]"}
========= after deletion ============

The Remove method has the following four kinds, according to the specific situation to choose the appropriate method:


--end

Scala's additions and deletions to MONGODB operations

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.