Java 操作 MongoDB

操作 MongoDB CRUD

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class TestCRUD {

    public static void main(String[] args) {
        MongoClient client = new MongoClient();
        MongoDatabase database = client.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("person");
        
        Document document = new Document("x",1);
        collection.insertOne(document);
        
        // 自定义类型
        MongoCollection<BasicDBObject> collection2 = database.getCollection("person",BasicDBObject.class);
        BasicDBObject basicDBObject = new BasicDBObject("y",2);
        collection2.insertOne(basicDBObject);
        
        FindIterable<Document> find = collection.find();
        MongoCursor<Document> iterator = find.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJson());
        }
        
        client.close();
    }
}

 

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