MongoDB java常用api

來源:互聯網
上載者:User

本篇文章主要介紹了MongoDB對應Java的常用增刪改查的api,以及和spring整合後mongoTemplate的常用方法使用,廢話不多說,直接上代碼:

1.首先上需要用到的兩個實體類User和Home,對應使用者和家鄉

import java.util.List;
import org.springframework.data.mongodb.core.mapping.Document;
/**
 * java類轉換為mongodb的文檔,它有以下幾種注釋:
 * 1.@Id - 文檔的唯一標識,在mongodb中為ObjectId,它是唯一的,通過時間戳記+機器標識+進程ID+自增計數器(確保同一秒內產生的Id不會衝突)構成。
 * 2.@Document - 把一個java類聲明為mongodb的文檔,可以通過collection參數指定這個類對應的文檔。
 * 3.@Indexed - 聲明該欄位需要索引,建索引可以大大的提高查詢效率。
 * 4.@Transient - 映射忽略的欄位,該欄位不會儲存到MongoDB
 * 5.@CompoundIndex - 複合索引的聲明,建複合索引可以有效地提高多欄位的查詢效率。
 * 6.@PersistenceConstructor - 聲明建構函式,作用是把從資料庫取出的資料執行個體化為對象。該建構函式傳入的值為從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.以下類MongoDBTest.java展示了mongodb的Java api常用的增刪改查的方法的使用

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 {
//建立一個MongoDB的資料庫連接對象,無參數的話它預設串連到當前機器的localhost地址,連接埠是27017。
mongo = new Mongo("192.168.225.101",27017);
//得到一個test的資料庫,如果mongoDB中沒有這個資料庫,當向此庫中添加資料的時候會自動建立
db = mongo.getDB("test");
db.authenticate("test", "test".toCharArray());
//擷取到一個叫做"user"的集合,相當於關係型資料庫中的"表"
user = db.getCollection("user");
}

/**
 * 查詢所有的集合名稱
 */
public void testGetAllCollections() {
Set<String> collectionNames = db.getCollectionNames();
for(String name:collectionNames) {
System.out.println("collectionName:"+name);
}
}

/**
 * 查詢所有的使用者資訊
 */
public void testFind() {
testInitTestData();
//find方法查詢所有的資料並返回一個遊標對象
DBCursor cursor = user.find();

while(cursor.hasNext()) {
print(cursor.next());
}
//擷取資料總條數
int sum = cursor.count();
System.out.println("sum==="+sum);
}

/**
 * 查詢第一條資料
 */
public void testFindOne() {
testInitTestData();
//只查詢第一條資料
DBObject oneUser = user.findOne();
print(oneUser);
}

/**
 * 條件查詢
 */
public void testConditionQuery() {
testInitTestData();
//查詢id=50a1ed9965f413fa025166db
DBObject oneUser = user.findOne(new BasicDBObject("_id",new ObjectId("50a1ed9965f413fa025166db")));
print(oneUser);

//查詢age=24
List<DBObject> userList1 = user.find(new BasicDBObject("age",24)).toArray();
print("        find age=24: ");
printList(userList1);

//查詢age>=23
List<DBObject> userList2 = user.find(new BasicDBObject("age",new BasicDBObject("$gte",23))).toArray();
print("        find age>=23: ");
printList(userList2);

//查詢age<=20
List<DBObject> userList3 = user.find(new BasicDBObject("age",new BasicDBObject("$lte",20))).toArray();
print("        find age<=20: ");
printList(userList3);

//查詢age!=25
List<DBObject> userList4 = user.find(new BasicDBObject("age",new BasicDBObject("$ne",25))).toArray();
print("        find age!=25: ");
printList(userList4);

//查詢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);

//查詢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 age not in[23,24,27]: ");
printList(userList6);

//查詢29>age>=20
List<DBObject> userList7 = user.find(new BasicDBObject("age",new BasicDBObject("$gte",20).append("$lt", 29))).toArray();
print("        find 29>age>=20: ");
printList(userList7);

//查詢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);

//和上面的查詢一樣,用的是QueryBuilder對象
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);

//查詢所有的使用者,並按照年齡升序排列
List<DBObject> userList9 = user.find().sort(new BasicDBObject("age",1)).toArray();
print("        find all sort age asc: ");
printList(userList9);

//查詢特定欄位
DBObject query1 = new BasicDBObject();//要查的條件 
        query.put("age", new BasicDBObject("$gt",20)); 
        DBObject field = new BasicDBObject();//要查的哪些欄位 
        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);
        
//查詢部分資料
        DBObject query2 = new BasicDBObject();//查詢條件
        query2.put("age", new BasicDBObject("$lt",27));
        DBObject fields = new BasicDBObject();//查詢欄位
        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);

//模糊查詢
DBObject fuzzy_query=new BasicDBObject();  
        String keyWord="zhang";  
        Pattern pattern = Pattern.compile("^" + keyWord + ".*$", Pattern.CASE_INSENSITIVE);  
        fuzzy_query.put("name", pattern);
        //根據name like zhang%查詢
        List<DBObject> userList12 = user.find(fuzzy_query).toArray();
        print("        select * from user where name like 'zhang*'");
        printList(userList12);

}

/**
 * 刪除使用者資料
 */
public void testRemoveUser() {
testInitTestData();
DBObject query=new BasicDBObject();  
//刪除age>24的資料
query.put("age", new BasicDBObject("$gt",24));
user.remove(query);
printList(user.find().toArray());
}

/**
 * 修改使用者資料
 */
public void testUpdateUser() {

//update(query,set,false,true);
//query:需要修改的資料查詢條件,相當於關係型資料庫where後的語句
//set:需要設的值,相當於關係型資料庫的set語句
//false:需要修改的資料如果不存在,是否插入新資料,false不插入,true插入
//true:如果查詢出多條則不進行修改,false:只修改第一條

testInitTestData();

//整體更新
DBObject query=new BasicDBObject(); 
query.put("age", new BasicDBObject("$gt",15));
DBObject set=user.findOne(query);//一定是查詢出來的DBObject,否則會丟掉一些列,整體更新
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, //需要修改的資料條件
set,//需要賦的值
false,//資料如果不存在,是否建立
false);//false只修改第一條,true如果有多條就不修改
printList(user.find().toArray());

//局部更新,只更改某些列
//加上$set會是局部更新,不會丟掉某些列,只把name更新為"jindazhong",年齡更新為123
BasicDBObject set1 = new BasicDBObject("$set", new BasicDBObject("name","jindazhong").append("age", 123));
user.update(query, //需要修改的資料條件
set1,//需要賦的值
false,//資料如果不存在,是否建立
false);//false只修改第一條,true如果有多條就不修改
printList(user.find().toArray());

//批次更新
// user.updateMulti(new BasicDBObject("age",new BasicDBObject("$gt",16)), 
// new BasicDBObject("$set", new BasicDBObject("name","jindazhong").append("age", 123)));
// printList(user.find().toArray());

}

/**
 * 初始化測試資料
 */
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", "小龍女");
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", "鳳姐");
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", "黃蓉");
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", "王語嫣");
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", "未知");
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();
}

/**
 * 列印資料
 * @param object
 */
public void print(Object objec

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.