Java 操作MongoDb 增删改查

—— 超级简单的CRUD操作适合新手… 写得不好请谅解,如有问题欢迎指正 —–
参考官方API文档:官方API文档


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import org.bson.Document;
import org.junit.Test;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;


/**
 * 
 * @author George
 * @Desciption
 * 简单操作mongodb:
 *  1.建立与mongodb连接 
 *  2.获取到具体的某个数据库 
 *  3.获取到该数据库的Collection
 *  4.对data进行简单的CRUD操作 
 *  
 *  @see https://docs.mongodb.com/getting-started/java/     <br>
 *       http://mongodb.github.io/mongo-java-driver/3.4/driver/ 
 *       
 */
public class MongoDbDemo {

    //数据库连接信息
    private MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
    private MongoDatabase db = mongoClient.getDatabase("demo_database");

    @Test
    public void creatConllectionTest() {
        try {
            db.createCollection("student");
        } finally {
            mongoClient.close();
        }
    }

    @Test
    public void insertOneTest() {
        try {
            db.getCollection("student").insertOne(
                    new Document()
                    .append("name", "Kim")
                    .append("class", "class_java")
                    .append("grades", Arrays.asList(
                            new Document()
                            .append("date", "2016-03-17")
                            .append("grade", "A")
                            .append("scope", 98),
                            new Document()
                            .append("date", "2016-07-17")
                            .append("grade", "A")
                            .append("scope", 95))));
        } finally {
            mongoClient.close();
        }
    }

    @Test
    public void insertManyTest() {
        try {
            MongoCollection<Document> demoCollection = db.getCollection("mongoDBDemo");
            List<Document> documents = new ArrayList<Document>();
            for (int i = 0; i < 10000; i++) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                Document doc = new Document()
                        .append("key", uuid)
                        .append("hashkey", uuid.hashCode());
                documents.add(doc);
            }
            demoCollection.insertMany(documents);
        } finally {
            mongoClient.close();
        }
    }

    @Test
    public void deleteOneTest() { 
        try {
            DeleteResult deleteOne = db.getCollection("mongoDBDemo").deleteOne(
                    new Document("key",0));
            System.out.println("deleteCount : " + deleteOne.getDeletedCount());
        } finally {
            mongoClient.close();
        }
    }

    @Test
    public void deleteManyTest() {
        try {
            //删除key中value小于等于10的data
            DeleteResult deleteMany = db.getCollection("mongoDBDemo").deleteMany(
                        new Document("key",new Document("$lte", 10)));
            System.out.println("deleteCount : " + deleteMany.getDeletedCount());
        } finally {
            mongoClient.close();
        }
    }

    @Test
    public void updateOneTest() {
        try {
            db.getCollection("student").updateOne(new Document("name", "Mike"),
                new Document("$set", new Document("class", "class_Python")));
        } finally {
            mongoClient.close();
        }
    }

    @Test
    public void updateManyTest() {
        try {
            db.getCollection("student").updateMany(
                    new Document("class", "class_java").append("grades.date", "2016-07-17"),
                    new Document("$set", new Document("grades.date", "2016-06-17")));
        } finally {
            mongoClient.close();
        }
    }

    /**
     * mongodb常用查询条件
     *  $lt:小于	$lte:小于等于
     *  $eq:等于   $ne:不等于
     *  $gt:大于	$gte:大于等于
     *  $in:存在   $nin:不存在
     *  $or:或	$and:且
     */
    @Test
    public void queryTest() {
        MongoCursor<Document> iterator = db.getCollection("account").find().filter(new Document("age", 
                                        new Document("$lte",24))).iterator();
        try {
            while (iterator.hasNext()) {
                String json = iterator.next().toJson();
                System.out.println(json);
            } 
        } finally {
            iterator.close();
            mongoClient.close();
        }
    }

    @Test
    public void queryAllTest1() {
        MongoCursor<Document> iterator = db.getCollection("account").find().iterator();
        try {
            while (iterator.hasNext()) {
                String json = iterator.next().toJson();
                System.out.println(json);
            } 
        } finally {
            iterator.close();
            mongoClient.close();
        }
    }

    @Test
    public void queryAllTest2() {   
        try {
            Block<Document> block = new Block<Document>() {
                public void apply(final Document document) {
                    System.out.println(document.toJson());
                }
            };
            db.getCollection("account").find().forEach(block);
        } finally {
            mongoClient.close();
        }
    }

    /**
     * 替换
     */
    @Test
    public void replaceTest() {
        try {
            db.getCollection("student").replaceOne(new Document("name", "Ruby"),
                    new Document("description", "cool man"));
        } finally {
            mongoClient.close();
        }
    }

    /**
     * 排序
     *  mongodb默认 -1:desc 1:asc
     */
    @Test
    public void sortDocumentTest() {
        try {
            FindIterable<Document> docs = db.getCollection("mongoDBDemo").find().sort(new Document("hashkey", -1))
                    .limit(100);
            for (Document doc : docs) {
                System.out.println(doc.toJson());
            } 
        } finally {
            mongoClient.close();
        }
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值