Mongodb-java-driver 3.2 version of commonly used code to complete (1)-Adding and deleting changes

Source: Internet
Author: User
Tags iterable mongoclient mul java keywords

The 3.x version of MongoDB's Java driver has a completely new design compared to 2.x, and there is a big difference between class libraries and usage methods. For example, replacing basicdbobject with document, using builders class to build Bson instead of direct input $ command and so on, this paper deals with the use of the common additions and deletions based on the 3.2 version. In order to avoid lengthy space, divided into additions and deletions, query, aggregation, geographical index and other parts.

Create a MAVEN project to add dependencies

<dependencies>    <dependency>        <groupId>org.mongodb</groupId>        <artifactid >mongodb-driver</artifactId>        <version>3.2.2</version>    </dependency></ Dependencies>
Non-MAVEN projects can download their own jar packages

Http://central.maven.org/maven2/org/mongodb/mongo-java-driver/3.2.2/mongo-java-driver-3.2.2.jar

To create a base code test connection

public class Cudexamples {public static void main (string[] args) throws ParseException {//Modify IP and Port mongoclient according to the actual environment lient = new Mongoclient ("localhost", 27017); Mongodatabase database = mongoclient.getdatabase ("Lesson"); mongocollection<document> MC = database.getcollection ("language");//Insert a document                Mc.insertone (" Oop "," Java ")); System.out.println (Mc.findoneanddelete new Document ("Oop", "Java"));        Mongoclient.close ();}}
If the output is document{{_id=573099877bee0e1710d52f4b, Oop=java}} indicates that the environment is configured correctly.

Transform the Cudexamples class to facilitate demonstration of the impact of each operation on the set

public class Cudexamples {public static void main (string[] args) throws ParseException {mongoclient mongoclient = new Mong OClient ("localhost", 27017); Mongodatabase database = mongoclient.getdatabase ("Lesson"); Cudexamples client = new Cudexamples (database); Client.show (); Mongoclient.close ();} Private Mongodatabase database;public cudexamples (mongodatabase database) {this.database = database;} public void Show () {mongocollection<document> MC = database.getcollection ("language");// Empties the collection before each execution to facilitate repeated mc.drop (), Mc.insertone ("Oop", "Java");p rintcollection ("Insert Java", MC);} Print the result set of the query public void printcollection (String doing, mongocollection<document> MC) {System.out.println (doing);        finditerable<document> iterable = Mc.find (); Iterable.foreach (New block<document> () {public void apply (Final Document document) {Syst            Em.out.println (document);        }        }); System.out.println ("------------------------------------------------------"); System.out.println ();}}

As shown in the preceding code, all operations are focused on the show () method and the collection is printed after execution to observe the effect on the collection. Below to populate the show () method, note the need to import updates.* statically

Import static com.mongodb.client.model.updates.*;

Mc.insertone ("Oop", "Java"));p rintcollection ("Insert Java", MC);//Insert a document with two fields doc = new Document ("Oop", "CSharp"). Append ("Copyright", "Microsoft"), Mc.insertone (DOC);p rintcollection ("Insert CSharp", MC) ;//Find and modify a document Mc.findoneandreplace ("Oop", "Java"), New Documents ("OOP", "Java"). Append ("Copyright", " Oracle "));p rintcollection (" Findandreplace java ", MC);//Delete a document Mc.deleteone (" Oop "," Java "); Printcollection ("Delete Java", MC);//Delete all documents Mc.deletemany (new document ());p rintcollection ("Delete all", MC);// Reinsert the test document Mc.insertone ("Oop", "Java"). Append ("Copyright", "Oracle")), Mc.insertone ("Oop", " CSharp "). Append (" Copyright "," Microsoft "));p rintcollection (" Insert Java,csharp and Swift ", MC);//$set The document has the specified field modified, No, add Mc.updatemany (New Document (), set ("Rank");p rintcollection ("$set all Rank", MC);//$unset Delete the field mc.updateone ("Oop", "CSharp"), unset ("rank");p rintcollection ("unset csharp rank", MC) when the specified field is present in the document; /$inc The specified field is added to the document, and no Mc.updateone (new document ("Oop", "CSharp"), Inc. ("Rank", "30"));p rintcollection ("$inc CSharp MC), Mc.updateone ("Oop", "CSharp"), Inc. ("Rank");p rintcollection ("$inc csharp rank", MC);//$ SETONINSERT specifies upsert=true when updating and actually triggers an insert operation Mc.updateone ("Oop", "Swift"). Append ("Copyright", "apple"), Setoninsert ("rank", +), new UpdateOptions (). Upsert (True));p rintcollection ("$setOnInsert rank for Swift", MC);//$ Mul multiplies Mc.updateone ("Oop", "Java"), Mul ("rank", 0.2));p rintcollection ("$mul java rank:0.2", MC);//$rename Rename Mc.updatemany (New Document (), rename ("Rank", "ranks"));p rintcollection ("$rename all rank to ranks", MC);//$min The smaller mc.updatemany between the current value and the specified value (new Document (), Min ("ranks", "H"));p rintcollection ("$min all Ranks:50", MC);//$max The larger mc.updatemany between the current value and the specified value (new Document (), Max ("ranks", +));p rintcollection ("$max all Ranks:40", MC);//$ Currentdatemc.updatemany ("Oop", "Java"), currentdate ("add");p RintcollectiOn ("$currentDate Java", MC);//$CURRENTTIMESTAMPMC. Updatemany ("Oop", "Java"), Currenttimestamp (" LastModified "));p rintcollection (" $currentTimestamp java ", MC);//$addToSet Add an element to the non-repeating collection mc.updatemany (The New Document (" Oop "," Java "), Addtoset (" keywords "," for "), Mc.updatemany (" Oop "," Java "), Addtoset (" keywords "," for "); Printcollection ("$addToSet java keywords:for", MC);//$addEachToSet add a set of elements to the non-repeating collection mc.updatemany ("Oop", " Java "), Addeachtoset (" keywords ", arrays.aslist (" while "," true "," Do "," new "," Override ")), Mc.updatemany (New Document ("Oop", "Java"), Addeachtoset ("keywords", arrays.aslist ("while", "true", "Do", "new", "Override")));p rintcollection (" $addEachToSet java keywords:while,true,do,new,override ", MC);//$popFirst Delete the first element Mc.updatemany (" Oop "," Java "), Popfirst (" keywords "));p rintcollection (" $popFirst java keywords ", MC);//$popLast Delete the last element Mc.updatemany (new Document ("Oop", "Java"), Poplast ("keywords"));p rintcollection ("$popLast Java keyworDS ", MC);//$pull Delete the specified element Mc.updatemany (" Oop "," Java "), Pull (" keywords "," new "));p rintcollection (" $pull Java keywords:new ", MC);//$pullByFilter Delete mc.updatemany based on filters (" Oop "," Java "), Pullbyfilter ( Filters.gte ("keywords", "true")));p rintcollection ("$pullByFilter java keywords:true", MC);//$pullAll Delete a set of elements Mc.updatemany ("Oop", "Java"), Pullall ("keywords", arrays.aslist ("while", "true", "Do", "new", " Override "));p rintcollection (" $pullAll java keywords ", MC);//$push Add an element to the Repeatable collection Mc.updatemany (" Oop "," Java "), push (" scores ");p Rintcollection (" $push java scores:89 ", MC);//$pushEach add a set of elements to a repeatable collection mc.updatemany (new Document ("Oop", "Java"), Pusheach ("scores", Arrays.aslist (), ()));p rintcollection ("$pushEach Java scores: 89,90,92 ", MC);//Inserts a set of elements Mc.updatemany (" Oop "," Java "), Pusheach (" scores ", Arrays.aslist (11, 12, 13) at the specified location in the collection. ), New Pushoptions (). Position (0)));p rintcollection ("$pushEach Java scores:11,12,13 at position 0", MC);Inserts a set of elements at a specified position in the collection and arranges the Mc.updatemany in reverse order ("OOP", "Java"), Pusheach ("scores", arrays.aslist (+), new Pushoptions (). Sort ( -1)));p rintcollection ("$pushEach Java scores:40,41 and sort ( -1)", MC);//Inserts a set of elements at a specified position in the collection, The first 3 Mc.updatemany are retained in reverse order ("OOP", "Java"), Pusheach ("scores", Arrays.aslist (max.), and New Pushoptions (). Sort ( -1). Slice (3));p rintcollection ("$pushEach Java scores:60,61 and sort ( -1) and slice (3)", MC);//Insert a set of inline documents Bson Bson = Pushe                              Ach ("experts", Arrays.aslist ("First", "Rod") Append ("Last", "Johnson"), New Document ("First", "Doug"). Append ("Last", "cutting")), Mc.updateone ("Oop", "Java"), Bson);p Rintcoll Ection ("$pushEach", MC),//combine combination Bsonbson = Combine (set ("Author", "James Gosling"), set ("Version", "8.0")); Mc.updateone ("Oop", "Java"), Bson);p rintcollection ("$combine", MC);
Finish


Mongodb-java-driver 3.2 version of commonly used code to complete (1)-Adding and deleting changes

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.