MongoDB Basic Operations _mongodb

Source: Internet
Author: User
Tags mongodb object model set set

MongoDB is a high performance NoSQL database based on document type, which has excellent performance under high concurrency, therefore, the use of MongoDB in the Internet industry will be very extensive.

Of course, MongoDB is mainly concerned about performance, so it does not provide functions similar to relational database transactions, for complex business and strict data consistency requirements are highly enterprise-class applications, do not recommend the use of MongoDB (online also have their own to implement the transaction submission scheme, but to achieve more cumbersome, A transactional solution similar to our early dbase,access file-type database.

In fact, also do not exclude some of the access pressure on the enterprise application, the transaction requirements of the data is not strict to the NoSQL database.

The Spring data Framework provides support for MongoDB, and everyone can go to http://mongojack.org/, and Http://www.springsource.org/spring-data/mongodb

For more information about MongoDB and sprig data for MongoDB.

Below, I use a simple example to explain the use of MongoDB, before you need to download MongoDB Java driver package, Spring Data commons, Spring data for MongoDB these component packages.

A total of two objects, customers, customer orders, a one-to-many relationship, one-way association.

Customer:

@Document
public class Customer {

@Id
private int id;
Private String Logincode;
private String name;
Private String pwd;

@Version
Private long varsion;

Private date Birthday = new Date ();

Private set<order> orders = new hashset<order> ();


Order:

@Document
public class Order {
@Id
private int id;
Private String Code;
Private String Ordername;


Configuration of Spring Data:

@Configuration
public class Mongoconfiguration {

Public @Bean mongodbfactory Mongodbfactory () throws Exception {
User name, password Authentication required
Usercredentials usercredentials = new Usercredentials ("Yq", "123");
return new Simplemongodbfactory (new Mongo (), "exam", usercredentials);
return new Simplemongodbfactory (new Mongo (), "exam");
}

Public @Bean mongotemplate Mongotemplate () throws Exception {
return new Mongotemplate (Mongodbfactory ());
}
}

Of course, the above information can be configured in XML, or it can be written in Java code as I have above.

Here to set up the exam library, you can mongodb command line, using the use command to establish, such as: "Uses exam, and then casually add something in the inside, the library is built." In addition, if you want to enable the authentication feature, you need to use the command to add users to a library (such as Db.adduser ("username", "password"), and start MongoDB with-auth parameters.

In the process of integration, if you report:

Tried to access Methodorg.springframework.core.GenericTypeResolver.getTypeVariableMap error because of the package version conflict, download the new Spring core package.

Here are some examples of how to use the API:

All we need is a mongotemplate

@Resource
Private Mongotemplate MT;



(1) Detect whether a space exists

Mt.collectionexists (Customer.class);


(2) Create new space

Mt.createcollection ("mycollection");


(3) Statistics of the total number of records, where query can be null, or a built with the conditions to check the data query, such as paging, please count, and then check the paging data

Mt.count (New Query (), customer.class);


(4) Delete space, where the data will be cleared together

Mt.dropcollection ("mycollection");


(5) Search by ID number

Customer C = Mt.findbyid (1, Customer.class);


(6) Delete the customer with ID number 1

Mt.remove (Mt.findbyid (1, customer.class));


(7) Delete customer with ID number less than 5
Mt.remove (New Query (Criteria.where ("id"). LT (5)), Customer.class);


(8) The query name is: Zhang 35, and the password is: 111 users
list<customer> cc = Mt.find (new Query (Criteria.where ("name"). Is ("Zhang 35"). and ("pwd"). Is ("a"), Customer.class) ;
or list<customer> cs = mt.find (new Query (Criteria.where ("name"). Is ("Zhang 35"). Andoperator (Criteria.where ("pwd"). is ("a")), Customer.class);

Note that there can only be one andoperator in a criteria, and if you want to write a parallel condition, just use and.


(9) The query name is: Zhang 35, or the password is: 111 users
List<customer> cs = mt.find (new Query (), New Criteria (). Oroperator (Criteria.where ("name"). Is ("Zhang 35"), Criteria.where ("pwd"). Is ("a")), Customer.class);


(10) Enquiries about customers with a date of birth less than June 6, 2013
List<customer> cs = mt.find (new Query (Criteria.where ("Birthday"). Lt (New Date ()), customer.class);

(11) Enquiries about customers with birth date equal to June 6, 2013
SimpleDateFormat SF = new SimpleDateFormat ("Yyyy-mm-dd-hh:mm:ss");
List<customer> cs = mt.find (new Query (
Criteria.where ("Birthday"). GTE (Sf.parse ("2013-06-06-00:00:00"))
. Andoperator (Criteria.where ("Birthday"). LTE (Sf.parse ("2013-06-09-23:59:59"))
), Customer.class);


(12) Inquiry order number is 0015 or 0018 of the customer
List<customer> cs = mt.find (new Query new Criteria ()
. WHERE ("Orders.code"). In ("0015", "0018")
), Customer.class);

Note that the MongoDB can be queried directly against the collection, for example, that the orders above are a set set.


(13) query contains four, and end of 0 customer
(regular expression, beginning with XX, please use ^, to xx end, please use $, do not write these two, express any)
List<customer> cs = mt.find (new Query new Criteria ()
. WHERE ("name"). Regex ("Four *0$")
), Customer.class);

Please note that MongoDB does not support regular queries on IDs.

(14) Modify the object property name, and modify it to synchronize the name of the property in the object, otherwise, this property value is null
Mt.updatemulti (New Query (), New Update (). Rename ("Password", "pwd"), "customer");


(15) Batch modification, the name of the customer ID of 100 changed to tomcat999, the password changed to 222
Mt.findandmodify New Query (Criteria.where ("id"). is (100)),
New Update (). Set ("Name", "tomcat999"). Set ("pwd", "222"),
Customer.class);

(16) Modify a single object
Customer cc = Mt.findbyid (MB, customer.class);
Cc.setpwd ("333");
Mt.save (CC);


(17) Sorting and paging implementation
Public page<customer> getcustomerbypage (int pageno, int pageSize, Map params) {

page<customer> page = new page<customer> (PageNo, pageSize);

Querying data
List<customer>data = MT
. Find (
New Query (). Skip (Page.getrowstartindex ())
. Limit (PageSize)
. with (New Sort (Sort.Direction.DESC, "_id"))

, Customer.class);

Page.setdata (data);

Total number of statistical records
Long Count = Mt.count (null, customer.class);
Page.setrowcounts (count);

return page;
}


Finally, a few examples of using MongoDB are given in the object design practice:

Object IDs are best designed to be of type string, and when added, MongoDB is automatically generated if the user does not assign a value, and of course you can use the UUID to assign it yourself.

Spring's encapsulation of mongodb occurs when there is a circular association between objects, and stack overflows occur when new and queried, and the current solution is:

A, cut off the two-way association. For example: A One-to-many two-way association, you can delete one side of the collection properties, multi-party reference to the use of dbref annotation annotations. The same is true of One-to-many, Many-to-many, and simplifying the relationships between objects as much as possible.

B, the relationship between the objects, it is best to establish directly into the relational database in the form of foreign key forms of the field, that is: not object-oriented way to build, this is "fish and bear, can not be both", in the pursuit of performance efficiency, abandon a better understanding of the object model.

Business system with strict transaction requirements, do not use MongoDB.

If there is an extreme high concurrency large data query, please use MongoDB, you can also save some of the data in the project in the MongoDB.

General concurrency modifications, which can be resolved using optimistic locking, Spring MongoDB supports @version logoff.


Also, the development of the best preparation of a graphical MongoDB management tools, such as: Mongocola, at any time to view the saved data live, easy to debug.

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.