zoukankan      html  css  js  c++  java
  • Java 连接 MongoDB

    在Java中使用MongoDB.

    import java.util.ArrayList;
    
    import org.bson.Document;
    
    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 static com.mongodb.client.model.Filters.*;
    
    public class TestMongoDriver {
    
        public static void main(String[] args) {
            try {
                // 连接到 MongoDB
                MongoClient mongoClient = new MongoClient("localhost",27017);
                // 打开数据库
                MongoDatabase database = mongoClient.getDatabase("test");
                
                MongoCollection<Document> collection = database.getCollection("person");
                // insert data
                Document document = new Document("title","MongoDB");
                ArrayList<Document> arrayList = new ArrayList<Document>();
                arrayList.add(document);
    //            collection.insertMany(arrayList);
                System.out.println("insert success");
                
                FindIterable<Document> find = collection.find(eq("name","one"));
                MongoCursor<Document> iterator = find.iterator();
                System.out.println("collection size:" + collection.count());
                
                while (iterator.hasNext()) {
                    System.out.println(iterator.next().toJson());
                    System.out.println(iterator.next());
                }
                
                mongoClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
    }
  • 相关阅读:
    多线程
    IO
    Collections工具类
    File类
    Map
    List与Set接口
    如何把数学作为一种工具
    包装类
    异常
    内部类
  • 原文地址:https://www.cnblogs.com/bwcode/p/8512475.html
Copyright © 2011-2022 走看看