mongodb实践 4

 

#存入数据

#基于document的数据

*定义一个文档对象@

---

> doc = { author: 'joe',
		  created : new Date('03/28/2009'),
		  title : 'Yet another blog post',
		  text : 'Here is the text...',
		  tags : [ 'example', 'joe' ],
		  comments : [ { author: 'jim', comment: 'I disagree' },
			      { author: 'nancy', comment: 'Good post' }
		  ]
		}
   

*保存该文档@

> db.posts.insert(doc);
 

*检索该文档@

> db.posts.find({"comments.author":"jim"});
		{ "_id" : ObjectId("4ee9550cbd3e00000000337e"), "author" : "joe", "created" : "Sat Mar 28 2009 00:00:00 GMT+0800", "title" : "Yet another blog post", "text" : "Here is the text...", "tags" : [ "example", "joe" ], "comments" : [
			{
				"author" : "jim",
				"comment" : "I disagree"
			},
			{
				"author" : "nancy",
				"comment" : "Good post"
			}
		] }
 

ps:在使用java driver 的时候,可以通过WriteConcern来返回异常信息,如@

db.test.insert(obj, WriteConcern.SAFE);
 

#mongodb优化

 

*使用索引@

db.things.ensureIndex({i:1});
 

 

*限制返回数据条数@

db.things.find().sort({i:1}).limit(10);
 

 

*只返回需要的列@

db.things.find({},{i2:true}).sort({i:-1}).limit(10);
 

返回i2域

db.things.find({},{i2:false}).sort({i:-1}).limit(10);
 

返回除i2的域,即i,i3

db.things.find({},{i2:false,_id:0}).sort({i:-1}).limit(10);
 

返回除i2、_id的剩余域

*还可以这么写(照搬官网示例)@

db.posts.find({}, {comments:{$slice: 5}}) // first 5 comments
		db.posts.find({}, {comments:{$slice: -5}}) // last 5 comments
		db.posts.find({}, {comments:{$slice: [20, 10]}}) // skip 20, limit 10
		db.posts.find({}, {comments:{$slice: [-20, 10]}}) // 20 from end, limit 10
 

 

*使用mongodb profiler(剖面测量仪,性能监视)@

> db.commandHelp("profile");
		help for: profile enable or disable performance profiling
		{ profile : <n> }
		0=off 1=log slow ops 2=log all
		http://www.mongodb.org/display/DOCS/Database+Profiler
		> db.setProfilingLevel(2);
		{ "was" : 0, "slowms" : 100, "ok" : 1 }
 

首选查一下帮助信息,然后将profillingLevel设置为2,was表示以前的设置。查看当前设置@

> db.getProfilingLevel();
		2
 

slowms值>100ms即被认为慢,可以通过如下命令修改默认值@

> db.setProfilingLevel(2,20)
		{ "was" : 2, "slowms" : 20, "ok" : 1 }
 

 

*明确的指明需要使用的索引@

> db.things.find({i:4}).hint({i:1});
		{ "_id" : ObjectId("4ee8510a0c16000000006ec9"), "i" : 4, "i2" : 16 }
		{ "_id" : ObjectId("4ee8514d0c16000000006edd"), "i" : 4, "i2" : 16, "i3" : 64 }
 

 

 

PS:贴一段使用索引的性能测试代码:(测试环境:window7 64 4G RAM)

 

 

 

  
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class PerformanceTest {

	private Mongo mongo = null;

	public PerformanceTest() {
	}

	private Mongo getInstance() {
		if (mongo == null)
			try {
				mongo = new Mongo();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (MongoException e) {
				e.printStackTrace();
			}
		return mongo;
	}

	/**
	 * 插入简单数据
	 */
	public static void Performance() {
		PerformanceTest pt = new PerformanceTest();
		Mongo mongo = pt.getInstance();
		DB db = mongo.getDB("mytest");
		/*// make a document and insert it
		BasicDBObject doc = new BasicDBObject();

		doc.put("name", "MongoDB");
		doc.put("type", "database");
		doc.put("count", 1);

		BasicDBObject info = new BasicDBObject();

		info.put("x", 203);
		info.put("y", 102);

		doc.put("info", info);
		Set<String> colls = db.getCollectionNames();
		for (String s : colls) {
			System.out.println(s);
		}*/

		DBCollection coll = db.getCollection("testCollection");
		int i = 0;

		
		DBObject myDoc = coll.findOne();
//		System.out.println(myDoc);

		for (i = 0; i < 6000000; i++) {
			coll.insert(new BasicDBObject().append("i", i).append("j", i).append("k", i));
		}

		/*DBCursor cur = coll.find();
		while (cur.hasNext()) {
			System.out.println(cur.next());
		}
		coll.drop();*/
		System.out.println(coll.count());
	}
	
	public static void creatIndex(){
		PerformanceTest pt = new PerformanceTest();
		Mongo mongo = pt.getInstance();
		
		DB db = mongo.getDB("mytest");
		DBCollection coll = db.getCollection("testCollection");
		coll.createIndex(new BasicDBObject("i", 1));
	}
	
	public static void query(){
		PerformanceTest pt = new PerformanceTest();
		Mongo mongo = pt.getInstance();
		DB db = mongo.getDB("mytest");
		
		BasicDBObject query = new BasicDBObject();
        query.put("i", new BasicDBObject("$gt", 1234).append("$lte", 1240));  // i.e.   20 < i <= 30
        DBCollection coll = db.getCollection("testCollection");
        DBCursor cur = coll.find(query);

        while(cur.hasNext()) {
            System.out.println(cur.next());
        }
	}
	
	public static void main(String[] args) {
		
		Long cost = System.currentTimeMillis();
		
		PerformanceTest pt = new PerformanceTest();
		Mongo mongo = pt.getInstance();
		DB db = mongo.getDB("mytest");
		
		DBCollection coll = db.getCollection("testCollection");
		System.out.println("count:"+coll.count());
		System.out.println(Integer.MAX_VALUE);
		System.out.println(Long.MAX_VALUE);
		//创建索引后,效率有大幅度的提升,6000000条数据(仅有一列)没有索引时查询耗时2865毫秒,
		//创建索引后,查询耗时111毫秒。
//		creatIndex();
		query();

//		Performance();
		cost = System.currentTimeMillis() - cost;
		System.out.println("cost:"+cost);
		
		/*
		coll.dropIndexes();
		coll.drop();
		db.dropDatabase();
		*/
	}

}
### 如何获取和使用华为云 OBS 桶的 AKSK #### 获取访问密钥(AKSK) 为了获得华为云 OBS 桶所需的访问密钥(Access Key ID, 简称 AK)以及秘密密钥(Secret Access Key, 简称 SK),需通过华为云控制台完成相应设置。具体流程是从华为云官方网站登录账号并进入控制面板,按照指引找到安全凭证部分来创建新的访问密钥组合[^1]。 一旦成功生成了一组 AK/SK 对,则应妥善保存这些信息,因为它们将在后续与 OBS 进行交互时作为身份验证依据被广泛应用于各种场景之中,比如上传文件、下载资源或是执行其他管理任务之前都需要利用此认证机制确保操作的安全性和合法性。 #### 使用访问密钥(AKSK) 当准备就绪之后,可以借助多种方式运用所取得的 AK 及其对应的 SK 来实现对 OBS 存储空间的操作: - **命令行工具**:对于希望通过脚本自动化处理大量数据的情况而言,可以通过安装 `obsutil` 工具来进行批量传输工作。初始化配置过程中会提示输入 AKSK 用于建立连接[^2]。 - **编程接口调用**:如果倾向于开发自定义应用程序的话,则可以选择适合项目的 SDK 库之一,并依照官方文档指导实例化客户端对象时传入必要的参数——即上述提到过的 AKSK 值。例如,在 Windows 平台上采用 Java 编程语言的情况下,可通过如下代码片段展示如何正确地构建一个能够正常工作的 ObsClient 实例[^4]: ```java import com.obs.services.ObsClient; public class Example { public static void main(String[] args) throws Exception { String ak = "your-access-key-id"; String sk = "your-secret-access-key"; String endpoint = "https://your-endpoint"; // 创建ObsClient实例 ObsClient obsClient = new ObsClient(ak, sk, endpoint); // 接下来可以根据需求编写更多逻辑... } } ``` 需要注意的是,在实际部署环境中应当采取适当措施保护好敏感资料不被泄露出去,同时定期更换密钥以增强安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值