Spring Data MongoDB III: Basic document Queries (query, basicquery) (i)
Learn MongoDB Six: MongoDB query (cursor action, cursor information) (iii)
A. Simple Introduction
Springdata MongoDB provides org.springframework.data.mongodb.core.MongoTemplate to the operation of MongoDB's find. We have an introduction to the basic document of the query, we introduce a paging query today, a paging query is returned to the matching document cursor, can arbitrarily modify the query restrictions, jumps, and sort order function.
We are querying when find () Method accepts the query type with Org.springframework.data.mongodb.core.query and Org.springframework.data.mongodb.core.query.BasicQuery
The query class provides methods with the ability to limit, skip, sort query restrictions, jumps, and sort order, and Basicquery inherits the query class.
Query |
Mongodb |
Description |
Query limit (int limit) |
Limit |
method is to limit the number of results returned by the cursor |
Query Skip (int skip) |
Skip |
Method can skip the number of bars of the specified value, return the result of the remaining number of bars, and be able to combine with the limit () method to achieve pagination effect |
Sort sort () is obsolete Now it's using query.with (sort) |
Sort |
method to sort the data according to the specified field. and use 1 or-one to specify that the sort is ascending or descending, similar to SQL's order by. |
two. Basic Paging
The query class provides methods with limit, skip, sort query restrictions, jumps, and sort order functions. We implement query querying paging
First step: Implement the Paging tool class
/** * Pagination * @author zhengcy * * @param <T> */public classpagemodel<t>{//result set privatelist<t> datas; Number of query records privateintrowcount; How many data privateintpagesize=20 per page; The first few pages of privateintpageno=1; Skip a few numbers privateintskip=0; /** * Total pages * @return */publicintgettotalpages () {return (rowcount+pagesize-1)/pagesize; } public List<t>getdatas () {return datas; } public void Setdatas (list<t>datas) {this.datas = datas; } public int GetRowCount () {return rowCount; } public void Setrowcount (int rowCount) {this.rowcount = RowCount; } public int getpagesize () {return pageSize; } public void SetPageSize (int pageSize) {this.pagesize = pageSize; } public int Getskip () {skip= (pageNo-1) *pagesize; return skip; } public void Setskip (int skip) {This.skip = skip; } public int Getpageno () {return pageno; } public void Setpageno (int pageno){This.pageno = PageNo; } }
Step Two: Implementing Paging
@Override public pagemodel<orders>getorders (pagemodel<orders> page, DBObject Queryobject, Stringcollectionname) { queryquery=newbasicquery (queryobject); Total Queries int count= (int) mongotemplate.count (query,orders.class); Page.setrowcount (count); Sort Query.with (new sort (DIRECTION.ASC, "Onumber")); Query.skip (Page.getskip ()). Limit (Page.getpagesize ()); List<orders>datas=mongotemplate.find (query,orders.class); Page.setdatas (datas); return page; }
Description
Sort:sort () is obsolete. Now it's using query.with (sort). With parameters is the sort class
The sort provides several constructors
Descriptive narrative of the method
(1) Sorting of a field
such as Onumber word orderby sequence
Query.with (New Sort (DIRECTION.ASC, "Onumber"));
(2) Assuming that multiple fields are ascending or descending at the same time
Sort
Query.with (New Sort (DIRECTION.ASC, "a", "B", "C"));
(3) Different fields are sorted according to different
List<sort.order>orders=new arraylist<sort.order> (); Orders.add (Newsort.order (DIRECTION.ASC, "a")); Orders.add (Newsort.order (Direction.desc, "B")); Query.with (Newsort (orders));
a ascending in descending order B
Step three: Test class
@Test public void Testlist () throws ParseException { pagemodel<orders>page=newpagemodel< Orders> (); Page.setpageno (1); Page=ordersdao.getorders (page, New Basicdbobject ("CNAME", "Zcy"), CollectionName); System.out.println ("Total:" +page.getrowcount ()); System.out.println ("Number of returned bars:" +page.getdatas (). Size ()); System.out.println (Jsonarray.fromobject (Page.getdatas ())); }
Query condition is cname=zcy
The Skip method is to skip the number of bars. And it's a one-way skip. Assuming that the collection is larger (such as a very large number of pages), skip will become slower, requiring many other processors (CPUs). This can affect performance.
third, advanced query paging
Returns the cursor to the matching document, with the ability to arbitrarily alter the function of the query restriction, jump, and sort order, the result of which we return to the pointer. I use the Morphia framework.
Morphia is an open source object-relational mapping framework for the MONGODB Database Java Edition drive very lightweight object encapsulation. We need to convert the DBObject obtained by DBCUROSR into our corresponding entity objects, so that we could manipulate the entities.
DBCUROSR is the object returned by the Find method of Dbcollection, able to set the skip, limit, Sot and other properties to run paged query
The first step: The entity ID to be annotated @id
Importcom.google.code.morphia.annotations.Id;
@Id
Privatestring ID;
@Id gaze indicates morphia which field is used as the document Id
If not added, this error will occur.
... More
caused by: com.google.code.morphia.mapping.validation.ConstraintViolationException : Number of violations:1
Noid complained Aboutcom.mongo.model.Orders. : No field is annotated with @Id; But it is required
atcom.google.code.morphia.mapping.validation.MappingValidator.validate (mappingvalidator.java:66 )
atcom.google.code.morphia.mapping.validation.MappingValidator.validate (mappingvalidator.java:155 )
atcom.google.code.morphia.mapping.MappedClass.validate (mappedclass.java:259)
Atcom.google.code.morphia.mapping.Mapper.addMappedClass (mapper.java:154)
Atcom.google.code.morphia.mapping.Mapper.addMappedClass (mapper.java:142)
Atcom.google.code.morphia.Morphia.map (morphia.java:55)
atcom.mongo.dao.impl.ordersdaoimpl.<init> (ordersdaoimpl.java:37)
Atsun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native Method)
Atsun.reflect.NativeConstructorAccessorImpl.newInstance (Unknown Source)
Atsun.reflect.DelegatingConstructorAccessorImpl.newInstance (Unknown Source)
Atjava.lang.reflect.Constructor.newInstance (Unknown Source)
Atorg.springframework.beans.BeanUtils.instantiateClass (beanutils.java:148)
... 29more
Step Two: Implement:
Privatemorphia Morphia; Public Ordersdaoimpl () {morphia= new Morphia (); Morphia.map (Orders.class); } @Override Public Pagemodel<orders>getorders (pagemodel<orders> page, DBObject Queryobject, Stringcollectionname) {dbobjectfilterdbobject=newbasicdbobject (); Filterdbobject.put ("_id", 0); Filterdbobject.put ("CNAME", 1); Filterdbobject.put ("Onumber", 1); Dbcursordbcursor=mongotemplate.getcollection (CollectionName). Find (Queryobject,filterdbobject); Sort Dbobjectsortdbobject=newbasicdbobject (); Sortdbobject.put ("Onumber", 1); Dbcursor.sort (Sortdbobject); Paged Query Dbcursor.skip (Page.getskip ()). Limit (Page.getpagesize ()); Total int count=dbcursor.count (); Circular pointer list<orders>datas=newarraylist<orders> (); while (Dbcursor.hasnext ()) {Datas.add (Morphia.fromdbobject (Orders.class, Dbcursor.next ())); } page.setrowcount (count); Page.setdAtas (datas); return page;}
when we start to run DAO, we first initialize the Morphia and add the entity classes we need to convert
Morphia=new morphia ();
Morphia. Map (Orders. Class);
Dbcursor.hasnext () infers if there is still the next document (dbobject), dbcursor.next () gets dbobject. We dbobject the corresponding entity class by Morphia.
Return the required fields through Filterdbobject settings at query time
MongoDB server Returns the result of the query cursor.hasnext () mongodb bulk size does not exceed the maximum bson document size However for most queries, the first batch returns 101 document or enough files more than 1 MB Maybe the batch size is 4 MB 101 hasnext
Four. Other methods of querying
mongotemplate . FindAll Query Collection All documents are equivalent to MongoDB's Db.collect.find ().
mongotemplate . FindByID queries the corresponding document _ID the document.
mongotemplate . Findandremove based on the query criteria. The query matches the document returned. and removed from the database.
When we query, this way the default is to use the index, for the data volume of the document, need to establish a suitable index. Faster query efficiency.
Spring Data MongoDB Five: Advanced document query (paging, Morphia) (ii)