MongoDB Driver相关

本文介绍如何使用MongoDB进行基本操作,包括连接数据库、指定数据库和集合、插入文档、执行多种查询(如$or、$and、$gt等)。并提供了一些重要的注意事项。

基本使用

//连接mongdb
MongoClient mongoClient = new MongoClient("localhost", 27017);
//指定数据库
DB db = mongoClient.getDB("mydb");
//指定集合
DBCollection coll = db.getCollection("mycol");
//插入文档{“name”: “mongo”, “info”: { “ver”: “3.0” } }
BasicDBObject doc = new BasicDBObject("name", "mongo").append("info", new BasicDBObject("ver", "3.0"));
coll.insert(doc);

//查找
// find all where i >= 50
BasicDBObject query = new BasicDBObject.append("i",
    new BasicDBObject.append(QueryOperators.GTE, 50));
DBCursor cursor = coll.find(query);
try {
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
} finally {
    cursor.close();
}

注意:
The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.
Typically you only create one MongoClient instance for a given database cluster and use it across your application.
When creating multiple instances:
- All resource usage limits (max connections, etc) apply per MongoClient instance
- To dispose of an instance, make sure you call MongoClient.close() to clean up resources.

简单查询举例:

// 或 $or
BasicDBObject queryObject = new BasicDBObject().append(  
    QueryOperators.OR,  
    new BasicDBObject[] { 
        new BasicDBObject("id", 1),  
        new BasicDBObject("id", 2) 
    });
cursor = coll.find(queryObject ); 

// 且$and
queryObject = new BasicDBObject().append(
    QueryOperators.AND,  
    new BasicDBObject[] { 
        new BasicDBObject("id", 10),  
        new BasicDBObject("name", "10")
    });  
cursor = coll.find(queryObject );  

// 大于 $gt
queryObject = new BasicDBObject().append("id",
    new BasicDBObject().append(QueryOperators.GT, 10));  
cursor = coll.find(queryObject );  

// 大于等于 $gte  
queryObject = new BasicDBObject().append("id",
    new BasicDBObject().append(QueryOperators.GTE, 11));  
cursor = coll.find(queryObject );   

//小于 $lt  
queryObject = new BasicDBObject().append("id"
    new BasicDBObject().append(QueryOperators.LT, 2));  
cursor = coll.find(queryObject );   

//小于等于 $lte  
queryObject = new BasicDBObject().append("id",
    new BasicDBObject().append(QueryOperators.LTE, 2));  
cursor = coll.find(queryObject );  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值