Mongodb-java-driver 3.2 version Common code full collation (2)-Query

Source: Internet
Author: User
Tags createindex iterable mongoclient sorts

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.

First look at the basic code of the class used for demonstration

Import static Com.mongodb.client.model.filters.*;import static Com.mongodb.client.model.projections.*;import static Com.mongodb.client.model.sorts.*;import Java.text.parseexception;import Java.util.arrays;import Org.bson.BsonType ; Import Org.bson.document;import Com.mongodb.block;import Com.mongodb.mongoclient;import Com.mongodb.client.finditerable;import Com.mongodb.client.mongocollection;import Com.mongodb.client.mongodatabase;import Com.mongodb.client.model.filters;import Com.mongodb.client.model.projections;public class Findexamples {public static void main (string[] args) throws ParseException {//Modify IP and port mongoclient mongoclient = new Mongoclient ("localhost", 27017) according to the actual environment; Mongodatabase database = mongoclient.getdatabase ("Lesson"); Findexamples client = new Findexamples (database); Client.show (); Mongoclient.close ();} Private Mongodatabase database;public findexamples (mongodatabase database) {this.database = database;} public void Show () {mongocollection<document> MC = Database.getcollEction ("blog");//emptying the collection before each execution to facilitate repeated mc.drop ();//Insert document for testing Doc1 = new documents ("title", "Good Day"). Append (" Owner "," Tom "). Append (" words "). Append (" Comments ", Arrays.aslist (New Document (" Author "," Joe "). Append (" Score ", 3 ). Append ("comment", "good"), new Document ("Author", "White"). Append ("Score", 1). Append ("comment", "Oh No"));D ocument DOC2 = new Document ("title", "Good"). Append ("owner", "John"). Append ("words"). Append ("Comments", Arrays.aslist ( New Document ("Author", "William"). Append ("Score", 4). Append ("comment", "good"), new document ("Author", "White"). Append ("Score", 6). Append ("comment", "very good")));D ocument doc3 = new Document ("title", "Good Night"). Append ("owner", "Mike"). Append ("words"). Append ("tag", Arrays.aslist (1, 2, 3, 4));D ocument doc4 = new Document ("title", "Happiness") . Append ("owner", "Tom"). Append ("words", 1480). Append ("tag", Arrays.aslist (2, 3, 4));D ocument doc5 = new Document ("title "A good Thing"). Append ("owner", "Tom"). Append ("Words", appenD ("tag", Arrays.aslist (1, 2, 3, 4, 5)); Mc.insertmany (Arrays.aslist (Doc1, Doc2, DOC3, doc4, DOC5));//test: Query All Finditerable <Document> iterable = Mc.find ();p Rintresult ("Find All", iterable);//todo: Will populate more query examples here}//print query result set public void        Printresult (String doing, finditerable<document> iterable) {System.out.println (doing); 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 the query operations are focused on the show () method, and the result set is printed after execution to observe the results of the query. Below to populate the show () method

Create a single-field index Mc.createindex (new document ("words", 1));//Create a composite index (also following the leftmost prefix principle) Mc.createindex (New document ("title", 1). Append ("Owner",-1));//Create full-text index Mc.createindex ("title", "Text");//Query All finditerable<document> iterable = Mc.find ();p Rintresult ("Find All", iterable);//Query title=gooditerable = mc.find (New Document ("title", "Good"))        ;p Rintresult ("Find Title=good", iterable); Query Title=good and owner=tomiterable = Mc.find (New Document ("title", "Good"). Append ("owner", "Tom"));p Rintresult ("        Find Title=good and Owner=tom ", iterable); The query title like%good% and owner=tomiterable = Mc.find (and (Regex ("title", "Good"), eq ("owner", "Tom")));p Rintresult (" Find title like%good% and Owner=tom ", iterable);//query all sorts by title iterable = Mc.find (). Sort (Ascending (" title ")); Printresult ("Find all and ascending title", iterable);//Query all sort by owner,title iterable = Mc.find (). Sort (Ascending ("owner" , "title"));p Rintresult ("Find All and Ascending owner,title", iterable);//query All by words reverse order iterable = Mc.find(). Sort (Descending ("words"));p Rintresult ("Find all and descending words", iterable);//query Owner=tom or words> 350iterable = Mc.find (New document ("$or", Arrays.aslist ("owner", "Tom"), New document ("Words", new document ("$GT", 350))));        Printresult ("Find Owner=tom or words>350", iterable); Returns the title and owner fields iterable = Mc.find (). Projection (Include ("title", "owner"));p Rintresult ("Find All" include (title,        Owner) ", iterable);        Returns fields other than title iterable = Mc.find (). Projection (Exclude ("title"));p Rintresult ("Find all exclude title", iterable);        Do not return the _id field iterable = Mc.find (). Projection (Excludeid ());p Rintresult ("Find all Excludeid", iterable); Returns the title and owner fields and does not return the _id field iterable = Mc.find (). Projection (Fields (include ("title", "owner"), Excludeid ()));        Printresult ("Find all include (Title,owner) and Excludeid", iterable); inline document Matching iterable = Mc.find (New document ("Comments.author", "Joe"));p Rintresult ("Find Comments.author=joe", iterable)        ; An example of the error,To query for comments containing the author is white and the score >2, the return result does not match the expected iterable = Mc.find ("Comments.author", "White"). Append (" Comments.score ", New Document (" $gt ", 2)));p Rintresult (" Find Comments.author=white and comments.score>2 (wrong) ",        iterable); The above requirements are spelled correctly iterable = Mc.find (Projections.elemmatch ("Comments", Filters.and (Filters.eq ("Author", "White"), FILTERS.GT ("Score", 2)));p Rintresult ("Find Comments.author=white and Comments.score>2 using Elemmatch", iterable)        ; Find title begins with good, and comments retains only one element iterable = Mc.find (Filters.regex ("title", "^good")). Projection (Slice ("comments        ", 1));p Rintresult (" Find regex ^good and slice comments 1 ", iterable); Full-text index lookup iterable = mc.find (Text ("good"));p Rintresult ("Text good", iterable);//filters built with title=gooditerable = Mc.find (eq ("title", "Good"));p rintresult ("Filters:title eq good", iterable);//$in equivalent to SQL initerable = Mc.find (In (" Owner "," Joe "," John "," William "));p Rintresult (" Filters:owner in Joe,john,william ", iterable);//$nin equivalent to SQL noT initerable = Mc.find (Nin ("owner", "Joe", "John", "Tom"));p Rintresult ("Filters:owner nin Joe,john,tom", iterable);// Query Inline Document iterable = Mc.find (In ("Comments.author", "Joe", "Tom"));p Rintresult ("Filters:comments.author in Joe,tom", iterable),//$ne not equal to iterable = Mc.find (NE ("words"));p rintresult ("filters:words ne", iterable);//$and Combination conditions iterable = Mc.find (and (eq ("owner", "Tom"), GT ("Words")));p rintresult ("Filters:owner eq Tom and Words GT", it erable);//a complex combination of iterable = Mc.find (and (or (EQ ("words"), eq ("words", "n")), or (eq ("owner", "Joe"), Size ("comments", 2)));p Rintresult ("Filters: (words=300 or words=400) and (Owner=joe or size (comments) =2)", iterable);// Query the 2nd element with an array value of 2 iterable = Mc.find (eq ("Tag.1", 2));p rintresult ("Filters:tag.1 eq 2", iterable);//query matches the array of all values iterable = Mc.find (All ("tags", arrays.aslist (1, 2, 3, 4)));p Rintresult ("Filters:tag match All (1, 2, 3, 4)", iterable);//$existsitera ble = Mc.find (exists ("tag"));p Rintresult ("filters:exists tag", iterable); iterable = Mc.find (Type ("words", bsontype.int32));p rintresult ("Filters:type Words is Int32", iterable); 

The query methods listed here can cover most of the development needs, please refer to the official documentation for more enquiry requirements.

Finish

Mongodb-java-driver 3.2 version Common code full collation (2)-Query

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.