MongoDB Java Driver 3.0

connection

数据库为每一个MongoDB数据库连接创建一个队列,一个连接可以保证先后顺序。
MongoClient自带连接池保持多个连接。DB and DBCollection are completely thread safe. In fact, they are cached so you get the same instance no matter what.我理解为对于每一个数据库或集合始终使用一个连接,保证数据一致。
程序退出时,调用MongoClient.close() to clean up resources。

// To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
// if it's a member of a replica set:
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
// or use a connection string
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019"));

MongoDatabase database = mongoClient.getDatabase("mydb");

创建DB

如果DB不存在,第一次操作(insert,update)时自动创建。

Collection

collection如果不存在,当插入第一个文档时自动创建。
DBCollection.createCollecton(String)特指创建固定集合。固定集合要事先创建,大小固定。新文档插入时自动淘汰最早的文档。固定集合使用场景是自动淘汰过期属性。用法之一是oplog(数据同步)

MongoCollection<Document> coll = db.getCollection("testCollection");
// 固定集合
database.createCollection("cappedCollection", new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));

Write Concern

MongoDB为了追求高速度,对于修改数据库的操作提供瞬间完成模式UNACKNOWLEDGED。函数发出命令后马上返回,不等待结果。

mongoClient.setWriteConcern(WriteConcern.JOURNALED);

查找

查找有两种方法

更新

不想写了,看代码吧

Index

index保存在system.index表中,驱动生成index名称的规则不同,可以用shell查看mycol.getIndexes()查看。

myColl.createIndex(new BasicDBObject("uid", 1).append("type", 1));//1升序 -1降序
myColl.createIndex(new BasicDBObject("type", -1));  

myColl.dropIndex("type_-1");//按名字删除
myColl.dropIndexes();//删除所有

实例代码,里面省略了异常处理。比如删除index,如果index不存在会报错的

package mongodb.demo;

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

import org.bson.Document;

import static com.mongodb.client.model.Filters.*;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.InsertOptions;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.InsertManyOptions;
import com.mongodb.client.model.UpdateOptions;

public class Curd {
    private MongoClient mongoClient;
    private MongoDatabase db; 
    private static Curd instance = null;
    public static Curd getInstance(){
        if(instance == null){
            instance = new Curd();
        }
        return instance;
    } 

    protected Curd() {
        // TODO Auto-generated constructor stub
    }

    public boolean init(){
        if(mongoClient != null) return true;
        mongoClient = new MongoClient("localhost",27017);
        if(mongoClient != null) {   
            db =  mongoClient.getDatabase("test");
            return true;
        }
        else {
            System.out.println("connect MongoDB server fail");
            return false;
        }
    }

    public static Document newMeter(int uid, int type, String value){
        Document meter = new Document("uid",uid)
        .append("type", type)
        .append("content", new Document("type",type).append("value", value)) 
        .append("updatetime", new Date());
        return meter;
    }

    public void insertOne(){
        //insert one
        MongoCollection<Document> coll = db.getCollection("meters");
        Document meter;
        InsertOptions option = new InsertOptions();
        option.writeConcern(WriteConcern.ACKNOWLEDGED);
        for(int i=0; i<50; i++){
            meter = newMeter(1234567,i,"insertOne");
            coll.insertOne(meter);          
        }       
    }

    public void insertMany(){
        List<Document> documents = new ArrayList<Document>();
        for(int i=0; i<50; i++){
            documents.add(newMeter(7654321,i,"insertMany"));
        }
        MongoCollection<Document> coll = db.getCollection("meters");
        InsertManyOptions option = new InsertManyOptions();
        option.ordered(true);
        coll.insertMany(documents,option);

    }


    public void findBasic(){
        MongoCollection<Document> coll = db.getCollection("meters");
        Document myDoc = coll.find(new BasicDBObject("uid",1234567).append("type",0)).first();
         System.out.println(myDoc);
    }

    public void findFilter(){
        MongoCollection<Document> coll = db.getCollection("meters");
        //import static com.mongodb.client.model.Filters.*; manully
        Document myDoc = coll.find(and(eq("uid",1234567),eq("type",0))).first();
        System.out.println(myDoc);
    }

    public void findWithCursor(){
        MongoCollection<Document> coll = db.getCollection("meters");
        MongoCursor<Document> cursor = coll.find(eq("uid",1234567)).iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }       
    }

    public void updateWhole(){
        MongoCollection<Document> coll = db.getCollection("meters");        

//      UpdateOptions options = new UpdateOptions();
//      options.upsert(true);//update or add
        coll.findOneAndUpdate(and(eq("uid",1234567),eq("type",0)), new Document("content.value","updateWhole"));
    }

    public void updateModifier(){
        MongoCollection<Document> coll = db.getCollection("meters");
        Document modifiedObject = new Document();
        modifiedObject.put("$set", new Document().append("comment", "updateModifier"));
        coll.updateOne(and(eq("uid",1234567),eq("type",0)),modifiedObject);
    }

    public void createIndex(){
        MongoCollection<Document> meters = db.getCollection("meters");
        meters.createIndex(new BasicDBObject("uid", 1).append("type", 1));
        meters.createIndex(new BasicDBObject("type", -1));  
    }

    public void dropIndex(){
        MongoCollection<Document> meters = db.getCollection("meters");
        meters.dropIndex("type_-1");
//      meters.dropIndexes();
    }

    public void drop(){
        MongoCollection<Document> meters = db.getCollection("meters");
        meters.dropCollection();        
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        Curd instance = Curd.getInstance();     
        instance.init();

        //drop collection
//      instance.drop();
        //insert one
//      instance.insertOne();

        //insert multi
//      instance.insertMany();      
//      
//      //find 
//      instance.findBasic();
//      instance.findFilter();
//      instance.findWithCursor();
//                  
//      //update
//      instance.updateWhole();
//      instance.findBasic();
//      instance.updateModifier();
//      instance.findBasic();
//      //create index
        instance.createIndex();
//      //drop index
        instance.dropIndex();
//      
//      //delete

    }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值