Introduction to the use of MongoDB framework Jongo

Source: Internet
Author: User
Tags findone int size mongoclient mongo shell

1. What can Jongo be used to do? The purpose of the Jongo framework is to enable query shells that can be used directly in MongoDB to be used directly in Java. On the homepage there is a very concise example: SHELL: This query method is supported by the MongoDB database Query method. Java DRIVER: Is the query method provided in the MongoDB Java Driver API Jongo: is the query provided by the Jongo framework. It can be seen that the intent of the Jongo framework is obvious.     2, Jongo download about MongoDB installation Here do not repeat, we can go to its official online view, the introduction of very detailed, http://docs.mongodb.org/manual/installation/. On Jongo's official website, the introduction of the Jongo framework relies on the Jackson 2.2.3, Bson4jackson 2.2.3 and Mongo Java Driver 2.11+, while the current version of Jongo is 1.0. Through my attempts, I found the following jar packages to be used in real-world applications:
Bson4jackson-2.3.1.jarjackson-annotations-2.4.1.jarjackson-core-2.4.1.1.jarjackson-databind-2.4.1.2.jarjongo-1.0.ja Rmongo-java-driver-2.12.2.jar
These jar packages can be found in the MAVEN repository, Http://mvnrepository.com/Jongo official website: Http://jongo.org/Jongo api:https://jongo.ci.cloudbees.com /job/jongo-ci/site/apidocs/index.htmljongo Github:https://github.com/bguerout/jongo 3, the use of Jongo Personinfo class:
1  Packagecom.jongo.enties;2  3  Public classPersonInfo {4  5  Private intID;6  PrivateString Person_name;7  PrivateString sex;8  PrivateString Relationship;9  Ten   PublicPersonInfo () { One   A  } - //Getter and Setter - @Override the   PublicString toString () { -   return"PersonInfo [id=" + ID + ", person_name=" +Person_name -+ ", sex=" + Sex + ", relationship=" + relationship + "]"; -  } +}
1) The first simple example
 PackageCom.jongo.demo;ImportJava.util.Iterator;ImportOrg.jongo.Jongo;Importorg.jongo.MongoCollection;ImportCom.jongo.enties.PersonInfo;ImportCom.mongodb.DB;Importcom.mongodb.MongoClient; Public classFirstdemo { Public Static voidMain (string[] args) {mongoclient MONGO=NULL; Try{MONGO=NewMongoclient ("localhost", 27017); DB DB= Mongo.getdb ("Jongo"); Jongo Jongo=NewJongo (DB); Mongocollection Person_info= Jongo.getcollection ("Person_info"); @SuppressWarnings ("Unchecked") Iterator<PersonInfo> all = (iterator<personinfo>) person_info.find (). As (PersonInfo.class);  while(All.hasnext ()) {PersonInfo PersonInfo=All.next (); System.out.println ("All:" +personInfo); } PersonInfo One= (PersonInfo) person_info.findone ("{id:1}"). As (PersonInfo.class); System.out.println ("One:" +One ); } Catch(Exception e) {e.printstacktrace (); } finally {   if(MONGO! =NULL) {mongo.close (); }  } }}
Operation Result: All:personinfo [id=1, Person_name=xiaoming, Sex=man, Relationship=friend]all:personinfo [id=2, Person_name= Xiaohong, Sex=male, Relationship=friend]one:personinfo [Id=1, Person_name=xiaoming, Sex=man, Relationship=Friend] &NBSP;2) Jongo save  PersonInfo PersonInfo = new PersonInfo (4, "Marry", "Male", "ClassMate");  Mcoll.save ( PersonInfo);  3) Jongo update in Jongo, the update syntax is a little different from the MONGO shell, and the modified query statement needs to be implemented by using with (), which can contain a string in or an object.   (1) person_info.update (new ObjectId ("53cb7d99b963ac657273328c")). With ("{$inc: {id:2}}");  original record: {"_id": ObjectId ("53cb7d99b963ac657273328c"), "id": 6, "Person_name": "Dark", "Sex": "Male", "relationship": "ClassMate" after update: {"_id": ObjectId ("53cb7d99b963ac657273328c"), "id": 8, "Person_name": "Dark", "Sex": "Male", "relationship": "Classm Ate "}  (2) person_info.update (" {person_name: ' Dark '} "). With (" {$set: {person_name: ' Dark Update '}} ");  original record: {"_id": ObjectId ("53cb7d91b963ac657273328a"), "id": 5, "Person_name": "Dark "," Sex ":" Male "," relationship ":" ClassMate "} after Update: {" _id ": ObjectId (" 53cb7d91b963ac657273328a ")," id ": 5," person _name ":" Dark update "," Sex ":" Male "," relationship ":" ClassMate "}  This update method only changes the first found record. In this way, all records Person_name to Dark will be updated: Person_info.update ("{person_name: ' Dark '}"). multi (). With ("{$set: {person_name: ') Dark Update '}} ");  (3) person_info.update (" {person_name: ' Dark '} "). With (new PersonInfo," Dark Update Object "," Man "," ClassMate "));  original record: {" _id ": ObjectId (" 53cb82ebb963ac657273329d ")," id ": 5," Person_name ":" Dark "," Sex ":" Male "," relationship ":" ClassMate "} after Update: {" _id ": ObjectId (" 53cb82ebb963ac657273329d ")," id ": Ten," Person_name ":" Dark Update Object "," Sex ":" Man "," relationship ":" ClassMate "}  (4) person_info.update (" {person_name: ' Dark '} "). With ( "{$set: {address:#}}", New Address ("0755", "Shenzhen"));  original record: {"_id": ObjectId ("53cb8310b963ac657273329e"), "id ": 5," Person_name ":" Dark "," Sex ":" Male "," relationship ":" ClasSmate "} after Update: {" _id ": ObjectId (" 53cb8310b963ac657273329e ")," id ": 5," Person_name ":" Dark "," Sex ":" Male "," Relationshi P ":" ClassMate "," address ": {" regioni d ":" 0755 "," Provincename ":" Shenzhen "}} 4) Jongo Insert (1) person_in Fo.insert ("{person_name: ' Insert Demo '}"); Result: {"_id": ObjectId ("53cb85cf2fd87f4058d1ff93"), "Person_name": "Insert Demo "}  (2) Insert a record personInfo personInfo = new PersonInfo (6," Marry Insert "," Male "," ClassMate ");p Erson_info.insert (personInfo); Result: {"_id": ObjectId ("53cb85e0b963ac65727332a3"), "id": 6, "Person_name": "Marry Insert", "Sex": "Male", "Relationship": "ClassMate"}  (3) Insert multiple records: PersonInfo PersonInfo2 = new PersonInfo (7, "Marry Insert2", "Male", " ClassMate ");p Erson_info.insert (Personinfo,personinfo2); Mode one Person_info.insert (new Object[]{personinfo,personinfo2});//Mode two  5) Jongo remove  person_info.remove (); Delete all   Person_info.remove (new ObjectId ("53CB87C02FD8F9FFD258CEB3"));  Person_info.remove ("{Person_name : ' MarRy Insert '} ');  6) Jongo query in Jongo, query and MONGO shell are almost identical. Let's take a look at how to query in the MONGO Shell: Original record: {"_id": ObjectId ("53cb8e8a2602b31118434306"), "id": 2, "Person_name": "Xiaohong", "Sex": "Male", "relationship": "Friend"}//for Number type > Db.person_info.find ({id:2}), or > Db.person_info.find ({"id": 2}); {"_id": ObjectId ("53cb8e8a2602b31118434306"), "id": 2, "Person_name": "Xiaohong", "Sex": "Male", "relationship": "Fr Iend "}//for String type > Db.person_info.find ({person_name: ' Xiaohong '});   or > Db.person_info.find ({"Person_name": "Xiaohong"}); {"_id": ObjectId ("53cb8e8a2602b31118434306"), "id": 2, "Person_name": "Xiaohong", "Sex": "Male", "relationship": "Fr Iend "}  So, how to query in Jongo? In fact, in the first simple example above we have seen,iterator<personinfo> all = (iterator<personinfo>) person_info.find (). As ( Personinfo.class); PersonInfo one = (PersonInfo) person_info.findone ("{id:1}"). As (Personinfo.class);  Let's take a look at this document structure: {"_id": ObjectId ("53cb9015b963ac65727332a4"), "id": 5, "PersoN_name ":" Dark "," Sex ":" Male "," relationship ":" ClassMate "," address ": {" RegionID ":" 0755 "," Provincename ":" Shenz Hen "}}, what do I do if I want to query the record of RegionID 0755 in address?   In the MONGO shell, we are querying this: Db.person_info.find ({"Address.regionid": "0755"}) or Db.person_info.find ({' Address.regionid ': ' 0755 ');  the same approach in Jongo, PersonInfo PersonInfo =   (PersonInfo) person_ Info.findone ("{address.regionid: ' 0755 '}"). As (Personinfo.class);  7) Jongo How to query the specified field (without querying a field)? We generally control whether the query field is displayed or not by {field:1} or {field:0}.   In the MONGO shell, the procedure is as follows:> Db.person_info.find ({},{person_name:1,_id:0}); Query out Person_name, do not query out _id. {"Person_name": "Xiaohong"} {"Person_name": "Dark"}  and in Jongo we need to use projection to reach this effect.   PersonInfo PersonInfo =    (PersonInfo) Person_info.findone (). Projection ("{person_name:1,id:1}"). As (personinfo.class);  8) Jongo sort, skip, limit, Hint, count in Jongo Sort, skip, limit, Hint, Count Basic and MONGO shell consistent. Suppose you have such a two-day record in the data collection:
>Db.person_info.find () {"_id": ObjectId ("53cb8e8a2602b31118434306"), "id": 2, "Person_name": "Xiaohong", "Sex": "Male", "relationship": "Frie nd }{ "_id": ObjectId ("53cb9015b963ac65727332a4"), "id": 5, "Person_name": "Dark", "Sex": "Male", "relationship": "Classmat E "," address ": {" RegionID ":" 0755 "," Provincename ":" Shenzhen "}}Iterator<PersonInfo> sort = (iterator<personinfo>) person_info.find (). Sort ("{id:1}"). As (PersonInfo.class);//sort {Field:1} ascending, {field:-1} descendingIterator<PersonInfo> skip = (iterator<personinfo>) person_info.find (). Skip (1). As (PersonInfo.class);//how many records are skipped when queryingIterator<PersonInfo> limit = (iterator<personinfo>) person_info.find (). Limit (2). As (PersonInfo.class);//querying a specified number of recordsIterator<PersonInfo> hint = (iterator<personinfo>) person_info.find (). Hint ("{person_name:-1}"). As (PersonInfo.class);//when you force a query to use the index specified by hint, be aware that you must establish a reverse index of the Person_name field beforehand.  LongLen = Person_info.count ("{id:5}");//Query the number of records that meet the criteria
9) Jongo OID in the mapping section, _id definition can be annotated @objectid to control, if you want to completely avoid using the original driver package Objectid, you can use the OID class provided by Jongo. Its usage is as follows:
Import Static Org.jongo.Oid.withOid;
PersonInfo PersonInfonew// @ObjectId String _id PersonInfo class, you need to define a field named _ID. and add @objectid annotation person_info.save (personInfo);p erson_info.find (withoid (personinfo._id)). As (PersonInfo. class // instead of new ObjectId (personinfo._id)
Jongo query template Almost all queries Jongo can be templated: Add Anchor #. Binding parameters can be Bson primitives or any complex type.
PersonInfo PersonInfo= Person_info.findone ("{id:#,person_name:#}", 2, "Xiaohong"). As (PersonInfo.class);//equivalent to FindOne ("{id:2,person_name: ' Xiaohong '}")PersonInfo PersonInfo2= Person_info.findone ("{address:#}",NewAddress ("0755", "Shenzhen")). As (PersonInfo.class);//equivalent to Db.person_info.findOne ({' Address.regionid ': ' 0755 ', ' address.privincename ': ' Shenzhen '});Iterator<PersonInfo> ite = (iterator<personinfo>) person_info.find ("{id:{$in: #}}", IDs). As (PersonInfo.class);//equivalent to Db.person_info.find ({id:{$in: [2,5]}});
One) Jongo query the following regular queries are equivalent:
 PersonInfo personInfo1 = Person_info.findone ( "{person_name:{$regex: #}}" , "dar.*"). As (Personinfo.   Class  ); PersonInfo PersonInfo2  = Person_info.findone ( "{person_name:{$regex: ' Dar.* '}} '). As (Personinfo.   Class  ); PersonInfo PersonInfo3  = Person_info.findone ( "{person_name:#}", Pattern.compile ("dar.*")). As (Personinfo.   Class  );  Pattern p  = pattern.compile ("dar.*" ); PersonInfo PersonInfo4  = Person_info.findone ( "{person_name:{$regex: '" +p+ "'}}"). As (Personinfo. Class ); 
Jongo aggregation operation (1) distinctlist<string> personnames = person_info.distinct ("Person_name"). As (String.class); List<address> addresses = person_info.distinct ("Address"). Query ("{id:5}"). As (address.class); int size = Person_ INFO.DISTINCT ("Address"). Query ("{id:5}"). As (Address.class). Size (); (2) Aggregation framework This feature can only be used in Mongo2.2 and above, all the aggregation operations such as $project, $match, $limit, $skip, $unwind, $group, $sort, are supported. On the official website there is an example:
Collection.aggregate ("{$project: {sender:1}}")          . and ("{$match: {tags: ' read '}}")          . and ("{ $limit: "). As          (Email. class);
4. Object mapping       query results are automatically mapped to the object, which relies on Jackson, involves the document structure, processes the list, and ignores missing attributes. Just need a parameterless constructor (or even a private constructor, if the object is immutable, annotation @jsoncreator can be used instead)       _ID is a unique identifier in each MongoDB document, if not set, It will be automatically generated, and when defined with Jongo, a property needs to be named _id or with @id annotations (alias @JsonProperty ("_id")), which can be defined using a specialized Objectid class or a simple string of @objectid annotations.         It is important to note that when you save a custom document _ID (any Java type except an array unexpectedly, as long as it is a unique value) it always needs to be manually set before persisting.         The following scenarios require manual setup of _id:        and the following are automatically generated:
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.