Java连接MongoDB示例

示例代码:

package com.zifeiy.snowflake.handle.etl.mongodb;

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

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;

public class MongodbTest {
    public static void main(String[] args) {
        MongoClient mongoClient = new MongoClient();
        MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb");
        System.out.println("connect to database[testdb] successfully");
        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("get collection[test] succeed");
        // insert
        List<Document> documents = new ArrayList<Document>();
        documents.add(new Document("name", "zifeiy")
                .append("age", 18)
                .append("sex", "boy")
                .append("weight", "0.1T"));
        documents.add(new Document("name", "celina")
                .append("age", 20)
                .append("sex", "girl")
                .append("weight", "50KG"));
        collection.insertMany(documents);
        System.out.println("documents insert succeed");
        // select
        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());
        }
    }
}

这里有一篇写的更详细的:http://www.cnblogs.com/wenbronk/p/6385935.html

    原文作者:MongoDB
    原文地址: https://www.cnblogs.com/zifeiy/p/10247860.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞