Java MongoDB入门

 

参考资料:Quick Tour

 

安装mongodb就不说了。

 

Maven Dependency(注:这里使用的是mongo-java-driver 3):

 

    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.0.2</version>
    </dependency>

 

 

测试代码(包含CRUD):

 

package com.tch.test.mongodb;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;


public class MongoDbWithJavaTest {

    public static void main(String[] args) {
        MongoClient mongo = null;
        try {
            // connect to mongodb
            mongo = new MongoClient("localhost", 27017);

            // list all databases
//            listDatabases(mongo);

            // get database named "test"
            MongoDatabase testDatabase = mongo.getDatabase("test");

            // list all collections(tables)
//            listCollections(testDatabase);

            MongoCollection<Document> userCollection = testDatabase.getCollection("user");

            // list all documents in user
//            listAllDocuments(userCollection);

            // insert new document
//            insert(userCollection);

            // list all documents in user after insert
//            listAllDocuments(userCollection);
//            listAllSpecifiedDocumentFields(userCollection);

            // list document with given filter
//            listDocumentWithFilter(userCollection);
//            
//            listDocumentWithFilterAndInReverseOrder(userCollection);
            
            // update document
//            updateOneDocument(userCollection);
//            updateAllDocument(userCollection);
//            
//            deleteOne(userCollection);
//            deleteMany(userCollection);
//            
//            listAllDocuments(userCollection);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mongo != null) {
                mongo.close();
                mongo = null;
            }
        }
    }
    
    public static void deleteOne(MongoCollection<Document> collection) {
        System.out.println("delete one records age less than 24");
        collection.deleteOne(Filters.lt("age", 24));
    }
    
    public static void deleteMany(MongoCollection<Document> collection) {
        System.out.println("delete all records age less than 24");
        collection.deleteMany(Filters.lt("age", 24));
    }

    public static void updateOneDocument(MongoCollection<Document> collection) {
        System.out.println("updateDocument : update one records that named 'dreamoftch' to 'ZhangSan'");
        collection.updateOne(Filters.eq("name", "dreamoftch"), new Document("$set", new Document("name", "ZhangSan")));
    }
    
    public static void updateAllDocument(MongoCollection<Document> collection) {
        System.out.println("updateDocument : update all records that named 'dreamoftch' to 'ZhangSan'");
        collection.updateMany(Filters.eq("name", "dreamoftch"), new Document("$set", new Document("name", "ZhangSan")));
    }

    public static void listDatabases(MongoClient mongo) {
        // list all databases
        MongoIterable<String> allDatabases = mongo.listDatabaseNames();
        for (String db : allDatabases) {
            System.out.println("Database name: " + db);
        }
    }

    public static void listCollections(MongoDatabase database) {
        // list all databases
        MongoIterable<String> allCollections = database.listCollectionNames();
        for (String collection : allCollections) {
            System.out.println("Collection name: " + collection);
        }
    }
    
    public static void listAllDocuments(MongoCollection<Document> collection) {
        System.out.println("begin get all document >>>>>>");
        for (Document document : collection.find()) {
            System.out.println(document);
        }
        System.out.println("finish get all document >>>>>>");
    }
    
    public static void listAllSpecifiedDocumentFields(MongoCollection<Document> collection) {
        System.out.println("begin get all document(exclude '_id') >>>>>>");
        for (Document document : collection.find().projection(Projections.exclude("_id"))) {
            System.out.println(document);
        }
        System.out.println("finish get all document(exclude '_id') >>>>>>");
    }
    
    public static void insert(MongoCollection<Document> collection){
        List<Document> documents = new ArrayList<Document>();
        for (int i = 0; i < 10; i++) {
            documents.add(new Document("name", "dreamoftch").append("age", (20+i)).append("createdDate", new Date()));
        }
        collection.insertMany(documents);
    }
    
    public static void listDocumentWithFilter(MongoCollection<Document> collection) {
        System.out.println("begin get document(name: dreamoftch, age > 25) >>>>>>");
        for (Document document : collection.find(Filters.and(Filters.eq("name", "dreamoftch"), Filters.gt("age", 25)))) {
            System.out.println(document);
        }
        System.out.println("finish get document(name: dreamoftch, age > 25) >>>>>>");
    }
    
    public static void listDocumentWithFilterAndInReverseOrder(MongoCollection<Document> collection) {
        System.out.println("begin get document(name: dreamoftch, age > 25) >>>>>>");
        for (Document document : collection.find(Filters.and(Filters.eq("name", "dreamoftch"), Filters.gt("age", 25))).sort(Sorts.descending("age"))) {
            System.out.println(document);
        }
        System.out.println("finish get document(name: dreamoftch, age > 25) >>>>>>");
    }
}

 

 

测试中间,每测试一个功能,都在mongodb的控制台通过 db.user.find()去查看执行之后的结果。

 

 

 

 

你可能感兴趣的:(java,mongodb)