MongoDB Java Common API

Source: Internet
Author: User
Tags findone

This article mainly introduces the MongoDB corresponding Java commonly used to delete and change the API, as well as and spring integration after mongotemplate common methods used, nonsense not much said, directly on the code:

1. First of all, the two entity classes that need to be used are user and home, corresponding users and native

Import java.util.List;
Import org.springframework.data.mongodb.core.mapping.Document;
/**
* The Java class is converted to a MongoDB document, which has the following kinds of annotations:
* 1. @Id-The unique identification of the document, which is objectid in MongoDB, is unique and consists of a timestamp + machine identification + process id+ counter (ensuring that the Id generated within the same second does not conflict).
* 2. @Document-Declare a Java class as a MongoDB document, and you can specify the corresponding document for this class by using the collection parameter.
* 3. @Indexed-Declare that the field requires an index, and indexing can greatly improve query efficiency.
* 4. @Transient-mapping ignored fields that are not saved to MongoDB
* 5. @CompoundIndex-Compound index declaration, build composite index can effectively improve the query efficiency of multiple fields.
* 6. @PersistenceConstructor-Declares a constructor to instantiate data taken from a database as an object. The value passed in by the constructor is the data fetched from the DBObject.
* @author Zhangguochen
*
*/
@Document (collection= "user")
public class User {

Private String ID;
private String name;
private int age;
Private list<string> interest;
Private String wife;
Private home home;

Public String getId () {
return ID;
}
public void SetId (String id) {
This.id = ID;
}
Public String GetName () {
return name;
}
public void setName1 (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int age) {
This.age = age;
}
Public list<string> getinterest () {
return interest;
}
public void Setinterest (list<string> interest) {
This.interest = interest;
}
Public String Getwife () {
return wife;
}
public void Setwife (String wife) {
This.wife = wife;
}
Public Home Gethome () {
return home;
}
public void Sethome (home home) {
This.home = home;
}
}

public class Home {

Private String address;

Public Home (String address) {
Super ();
this.address = address;
}
Public String getaddress () {
return address;
}
public void setaddress (String address) {
this.address = address;
}
}


2. The following classes of Mongodbtest.java show the use of the MongoDB Java API commonly used to delete and modify methods

Import java.util.List;
Import Java.util.Set;
Import Java.util.regex.Pattern;
Import Junit.framework.TestCase;
Import Org.bson.types.ObjectId;
Import Org.junit.Before;
Import Org.junit.BeforeClass;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;
Import Com.mongodb.Mongo;
Import Com.mongodb.QueryBuilder;
Import com.mongodb.QueryOperators;


public class Mongodbtest extends testcase{

Mongo Mongo = null;
DB db = null;
Dbcollection user = null;

@BeforeClass
public static void Setupbeforeclass () throws Exception {
}

@Before
public void SetUp () throws Exception {
Create a MongoDB database connection object, with no parameters it defaults to the localhost address of the current machine and the port is 27017.
MONGO = new MONGO ("192.168.225.101", 27017);
Get a database of test, if the database is not in the MongoDB, when you add data to this library will automatically create
db = Mongo.getdb ("test");
Db.authenticate ("Test", "Test". ToCharArray ());
Gets a collection called "User", which is equivalent to "table" in a relational database
user = Db.getcollection ("user");
}

/**
* Query all the collection names
*/
public void Testgetallcollections () {
set<string> collectionnames = Db.getcollectionnames ();
for (String name:collectionnames) {
System.out.println ("CollectionName:" +name);
}
}

/**
* Query all the user information
*/
public void Testfind () {
Testinittestdata ();
The Find method queries all data and returns a Cursor object
dbcursor cursor = User.find ();

while (Cursor.hasnext ()) {
Print (Cursor.next ());
}
Get the total number of data bars
int sum = Cursor.count ();
System.out.println ("sum===" +sum);
}

/**
* Query the first piece of data
*/
public void Testfindone () {
Testinittestdata ();
Query only the first piece of data
DBObject Oneuser = User.findone ();
Print (Oneuser);
}

/**
* Condition Query
*/
public void Testconditionquery () {
Testinittestdata ();
Query id=50a1ed9965f413fa025166db
DBObject Oneuser = User.findone (New Basicdbobject ("_id", New ObjectId ("50a1ed9965f413fa025166db"));
Print (Oneuser);

Query age=24
list<dbobject> userList1 = User.find (New Basicdbobject ("Age"). ToArray ();
Print ("Find age=24:");
Printlist (USERLIST1);

Query age>=23
list<dbobject> userList2 = User.find (New Basicdbobject ("Age", New Basicdbobject ("$gte")). ToArray ();
Print ("Find age>=23:");
Printlist (USERLIST2);

Query age<=20
list<dbobject> userList3 = User.find (New Basicdbobject ("Age", New Basicdbobject ("$lte")). ToArray ();
Print ("Find age<=20:");
Printlist (USERLIST3);

Query age!=25
list<dbobject> userList4 = User.find (New Basicdbobject ("Age", New Basicdbobject ("$ne")). ToArray ();
Print ("Find age!=25:");
Printlist (USERLIST4);

Query Age in[23,24,27]
list<dbobject> userList5 = User.find (New Basicdbobject ("Age", New Basicdbobject (Queryoperators.in,new int[]{ 23,24,27})). ToArray ();
Print ("Find agein[23,24,27]:");
Printlist (USERLIST5);

Query age not in[23,24,27]
list<dbobject> UserList6 = User.find (New Basicdbobject ("Age", New Basicdbobject (Queryoperators.nin,new int[]{ 23,24,27})). ToArray ();
Print ("Find is not in[23,24,27]:");
Printlist (USERLIST6);

Query 29>age>=20
list<dbobject> userList7 = User.find (New Basicdbobject ("Age", New Basicdbobject ("$gte"). Append ("$lt", 29)). ToArray ();
Print ("Find 29>age>=20:");
Printlist (USERLIST7);

Query age>24 and name= "Zhangguochen"
Basicdbobject query = new Basicdbobject ();
Query.put ("Age", New Basicdbobject ("$gt", 24));
Query.put ("name", "Zhangguochen");
list<dbobject> userList8 = user.find (query). ToArray ();
Print ("Find age>24 and Name= ' Zhangguochen ':");
Printlist (USERLIST8);

As with the query above, the QueryBuilder object is used
QueryBuilder QueryBuilder = new QueryBuilder ();
Querybuilder.and ("Age"). GreaterThan (24);
Querybuilder.and ("name"). Equals ("Zhangguochen");
list<dbobject> userList82 = User.find (Querybuilder.get ()). ToArray ();
Print ("QueryBuilder find age>24 and Name= ' Zhangguochen ':");
Printlist (userList82);

Query all users and arrange them in ascending order of age
list<dbobject> UserList9 = User.find (). Sort (New Basicdbobject ("Age", 1)). ToArray ();
Print ("Find all sort Age ASC:");
Printlist (USERLIST9);

Query specific fields
DBObject Query1 = new Basicdbobject ()/The condition to be checked
Query.put ("Age", New Basicdbobject ("$gt", 20));
DBObject field = new Basicdbobject ()//what fields to check
Field.put ("name", true);
Field.put ("Age", true);
List<dbobject> Userlist10=user.find (Query1,field). ToArray ();
Print ("Select Name,age where age>20");
Printlist (USERLIST10);

Querying part of the data
DBObject Query2 = new Basicdbobject ()//Query condition
Query2.put ("Age", New Basicdbobject ("$lt", 27));
DBObject fields = new Basicdbobject ()//query field
Fields.put ("name", true);
Fields.put ("Age", true);
list<dbobject> userList11 = User.find (Query2, fields, 1, 1). ToArray ();
Print ("Select Age,name from user skip 1 Limit 1:");
Printlist (USERLIST11);

Fuzzy query
DBObject fuzzy_query=new basicdbobject ();
String keyword= "Zhang";
Pattern pattern = pattern.compile ("^" + KeyWord + ". *$", pattern.case_insensitive);
Fuzzy_query.put ("name", pattern);
Query based on name like zhang%
list<dbobject> userList12 = User.find (fuzzy_query). ToArray ();
Print ("SELECT * from user where name is like ' zhang* '");
Printlist (userList12);

}

/**
* Delete user Data
*/
public void Testremoveuser () {
Testinittestdata ();
DBObject query=new basicdbobject ();
To delete age>24 data
Query.put ("Age", New Basicdbobject ("$gt", 24));
User.remove (query);
Printlist (User.find (). ToArray ());
}

/**
* Modify User Data
*/
public void Testupdateuser () {

Update (QUERY,SET,FALSE,TRUE);
Query: A data query condition that needs to be modified, equivalent to the statement after the relational database where
Set: A value that needs to be set, equivalent to the SET statement of a relational database
False: Data that needs to be modified if it does not exist, inserts new data, False does not insert, true inserts
True: If more than one query is not modified, false: Only the first article is modified

Testinittestdata ();

Overall update
DBObject query=new basicdbobject ();
Query.put ("Age", New Basicdbobject ("$gt", 15));
DBObject set=user.findone (query);/must be the dbobject, or you will lose some columns, the overall update
Set.put ("name", "ABC");
Set.put ("age", 19);
Set.put ("Interest", new string[]{"Hadoop", "study", "MongoDB"});
DBObject zhangguochenaddress = new Basicdbobject ();
Zhangguochenaddress.put ("Address", "Henan");
Set.put ("Home", zhangguochenaddress);
User.update (query,//data conditions that need to be modified)
set,//value to be assigned
false,//data is new if it does not exist
FALSE);//false only modifies the first article, true if there are more than one
Printlist (User.find (). ToArray ());

Local update, only some columns are changed
Plus $set will be a local update, will not lose some columns, only the name update to "Jindazhong", age update to 123
Basicdbobject Set1 = new Basicdbobject ("$set", New Basicdbobject ("name", "Jindazhong"). Append ("Age", 123);
User.update (query,//data conditions that need to be modified)
set1,//value to be assigned
false,//data is new if it does not exist
FALSE);//false only modifies the first article, true if there are more than one
Printlist (User.find (). ToArray ());

Batch Update
User.updatemulti (New Basicdbobject ("Age", New Basicdbobject ("$gt", 16)),
New Basicdbobject ("$set", New Basicdbobject ("name", "Jindazhong"). Append ("Age", 123));
Printlist (User.find (). ToArray ());

}

/**
* Initialization of test data
*/
public void Testinittestdata () {
User.drop ();
DBObject zhangguochen = new Basicdbobject ();
Zhangguochen.put ("name", "Zhangguochen");
Zhangguochen.put ("Age", 25);
Zhangguochen.put ("Interest", new string[]{"Hadoop", "study", "MongoDB"});
DBObject zhangguochenaddress = new Basicdbobject ();
Zhangguochenaddress.put ("Address", "Henan");
Zhangguochen.put ("Home", zhangguochenaddress);

DBObject Jindazhong = new Basicdbobject ();
Jindazhong.put ("name", "Jindazhong");
Jindazhong.put ("Age", 21);
Jindazhong.put ("Interest", new string[]{"Hadoop", "MongoDB"});
Jindazhong.put ("Wife", "Dragon Girl");
DBObject jindazhongaddress = new Basicdbobject ();
Jindazhongaddress.put ("Address", "Shanghai");
Jindazhong.put ("Home", jindazhongaddress);

DBObject Yangzhi = new Basicdbobject ();
Yangzhi.put ("name", "Yangzhi");
Yangzhi.put ("Age", 22);
Yangzhi.put ("Interest", new string[]{"shopping", "Sing", "Hadoop"});
DBObject yangzhiaddress = new Basicdbobject ();
Yangzhiaddress.put ("Address", "Hubei");
Yangzhi.put ("Home", yangzhiaddress);

DBObject Diaoyouwei = new Basicdbobject ();
Diaoyouwei.put ("name", "Diaoyouwei");
Diaoyouwei.put ("Age", 23);
Diaoyouwei.put ("Interest", new string[]{"Notejs", "Sqoop"});
DBObject diaoyouweiaddress = new Basicdbobject ();
Diaoyouweiaddress.put ("Address", "Shandong");
Diaoyouwei.put ("Home", diaoyouweiaddress);

DBObject Cuichongfei = new Basicdbobject ();
Cuichongfei.put ("name", "Cuichongfei");
Cuichongfei.put ("Age", 24);
Cuichongfei.put ("Interest", new string[]{"Ebsdi", "DQ"});
Cuichongfei.put ("wife", "Sister Feng");
DBObject cuichongfeiaddress = new Basicdbobject ();
Cuichongfeiaddress.put ("Address", "Shanxi");
Cuichongfei.put ("Home", cuichongfeiaddress);

DBObject Huanghu = new Basicdbobject ();
Huanghu.put ("name", "Huanghu");
Huanghu.put ("Age", 25);
Huanghu.put ("Interest", new string[]{"shopping", "study"});
Huanghu.put ("wife", "Huang Rong");
DBObject huanghuaddress = new Basicdbobject ();
Huanghuaddress.put ("Address", "Guangdong");
Huanghu.put ("Home", huanghuaddress);

DBObject Houchangren = new Basicdbobject ();
Houchangren.put ("name", "Houchangren");
Houchangren.put ("Age", 26);
Houchangren.put ("Interest", new string[]{"DotA", "DQ"});
DBObject houchangrenaddress = new Basicdbobject ();
Houchangrenaddress.put ("Address", "Shandong");
Houchangren.put ("Home", houchangrenaddress);

DBObject Wangjuntao = new Basicdbobject ();
Wangjuntao.put ("name", "Wangjuntao");
Wangjuntao.put ("Age", 27);
Wangjuntao.put ("Interest", new string[]{"Sport", "study"});
Wangjuntao.put ("wife", "Wang");
DBObject wangjuntaoaddress = new Basicdbobject ();
Wangjuntaoaddress.put ("Address", "Hebei");
Wangjuntao.put ("Home", wangjuntaoaddress);

DBObject Miaojiagui = new Basicdbobject ();
Miaojiagui.put ("name", "Miaojiagui");
Miaojiagui.put ("Age", 28);
Miaojiagui.put ("Interest", new string[]{"Hadoop", "study", "Linux"});
Miaojiagui.put ("wife", null);
DBObject miaojiaguiaddress = new Basicdbobject ();
Miaojiaguiaddress.put ("Address", "unknown");
Miaojiagui.put ("Home", miaojiaguiaddress);

DBObject longzhen = new Basicdbobject ();
Longzhen.put ("name", "Longzhen");
Longzhen.put ("Age", 29);
Longzhen.put ("Interest", new string[]{"study", "Cook"});
Longzhen.put ("wife", null);
DBObject longzhenaddress = new Basicdbobject ();
Longzhenaddress.put ("Address", "Sichuan");
Longzhen.put ("Home", longzhenaddress);

User.insert (Zhangguochen);
User.insert (Jindazhong);
User.insert (Yangzhi);
User.insert (Diaoyouwei);
User.insert (Cuichongfei);
User.insert (Huanghu);
User.insert (Houchangren);
User.insert (Wangjuntao);
User.insert (Miaojiagui);
User.insert (Longzhen);
}

public void Testremove () {
User.drop ();
}

/**
* Print Data
* @param Object
*/
public void print (Object objec

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.