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

 

posted on 2018-03-06 09:26  darkcode  阅读(591)  评论(0编辑  收藏  举报