java连接mongodb

 

    static MongoClient mongoClient = null;
    static {
         System.out.println("===============MongoDBUtil初始化========================");
         String ip = "47.104.105.175";
         int port =27017;
         mongoClient = new MongoClient(ip, port);
         // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:
         // boolean auth = db.authenticate(myUserName, myPassword);
         Builder options = new MongoClientOptions.Builder();
         options.cursorFinalizerEnabled(true);
         // options.autoConnectRetry(true);// 自动重连true
         // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
         options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100
         options.connectTimeout(30000);// 连接超时,推荐>3000毫秒
         options.maxWaitTime(5000); //
         options.socketTimeout(0);// 套接字超时时间,0无限制
         options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
         options.writeConcern(WriteConcern.SAFE);//
         options.build();
        }

//获取database

MongoDatabase database = MongoDb.mongoClient.getDatabase(dbName);
        System.out.println("MongoDatabase inof is : "+database.getName());

要创建集合,可使用 com.mongodb.DB 类的 createCollection()方法。

MongoCollection<Document> collection = database.getCollection(collName);

//获取当前库的所有集合名称

for (String name : database.listCollectionNames()) {
            System.out.println(name);
        }

要将文档插入到MongoDB中,使用com.mongodb.DBCollection类的insertOne()方法。

        Document document = new Document().append("description","database").append("likes", 30).append("by", "yiibai point");
        collection.insertOne(document);
        将集合遍历
        collection.find().forEach(printBlock);

static Block<Document> printBlock = new Block<Document>() {
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };

多行插入

Document doc1 = new Document("name", "Amarcord Pizzeria")
                   .append("contact", new Document("phone", "264-555-0193")
                                           .append("email", "amarcord.pizzeria@example.net")
                                           .append("location",Arrays.asList(-73.88502, 40.749556)))
                   .append("stars", 2)
                   .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));


        Document doc2 = new Document("name", "Blue Coffee Bar")
                       .append("contact", new Document("phone", "604-555-0102")
                                               .append("email", "bluecoffeebar@example.com")
                                               .append("location",Arrays.asList(-73.97902, 40.8479556)))
                       .append("stars", 5)
                       .append("categories", Arrays.asList("Coffee", "Pastries"));
    
        List<Document> documents = new ArrayList<Document>();
        documents.add(doc1);
        documents.add(doc2);
    
        collection.insertMany(documents);

更新文档

collection.updateOne(Filters.eq("_id",new ObjectId("5bd95a9747f93726b40cd23b") ),new Document("$set", new Document("name", "user30")));
        collection.updateOne(Filters.eq("name", "user28"),new Document("$set", new Document("name", "user29")));

删除文档

要从集合中删除第一个文档,需要首先使用findOne()方法选择文档,然后使用com.mongodb.DBCollection类的remove()方法。

collection.deleteOne(Filters.eq("description","database"));

 
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) >>>>>>");
    }
}

while (cursor.hasNext()) {
            Document next = cursor.next();
            System.out.println(next.toString());
        }

高级查询

MongoCursor<Document> cursor = collection.find(Filters.and(Filters.eq("name", "user30"),Filters.eq("age", 30))).iterator();

MongoCursor<Document> cursor = collection.find(Filters.or(Filters.eq("name", "user30"),Filters.eq("name", "Amarcord Pizzeria"))).iterator();

 

参考文档:

https://www.yiibai.com/mongodb/mongodb_java.html

https://www.cnblogs.com/sa-dan/p/6836055.html

https://blog.csdn.net/sunhuwh/article/details/46406253

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值