mongo小结和使用示例

简介:

mongo小结(>=2.2)

1、存储模式:面向集合存储,模式自由; GridFS大文件存储(16M)

2、容灾类型:主从复制(Replication)、Replica Set(自动选取主节点)、Sharding + Replica Set。

说明:mongo的Replication采用日志+批量更新方式,效率比直接更新高,Replication更新期间,从节点读性能受影响(锁机制导致)。

3、支持CRUD 和 Fast In-Place Updates(文档内更新)。

说明:Fast In-Place Updates支持快速更新文档自身内容,对于不影响文档大小的更新,效率比覆盖更新整个文档效率高。为了支持改变文档大小的文档内更新,mongo内部采用padding,即采用比文档略大的空间存储文档,当更新导致文档大小改变时,如改变大小不超过padding大小,就地更新,无须另外存储。padding比例由mongo自身决定。

4、读写锁,写锁优先

说明:mongo的锁机制对于解释mongo运行效率很重要。常见需要写锁的操作:insert、update、remove、eval(执行命令或脚本)、createIndex(创建索引需锁定整个collection,数据大时,相当耗时)、replication、TTL的定期删除。

5、存储机制:mmap file + 内存索引。完全由OS处理缓存。磁盘空间预分配(默认2G)。

说明:mongo将内存管理和缓存都交给OS。内存优先让给索引使用。当索引大于内存大小时,将影响各种操作。当"工作集"(热门数据)+索引 大于 内存时,查询性能受影响。

6、集合类型:普通集合、TTL Collection(淘汰过期数据)、 Capped Collection(定长集合,FIFO)

7、同步:拷贝集合数据+日志同步

8、相对丰富的运维工具和shell客户端

使用示例

复制代码
// this header should be first to ensure that it includes cleanly in any context
#include "mongo/client/dbclient.h"

#include <iostream>
#include <vector>
#include <string>

#ifndef verify
#  define verify(x) MONGO_verify(x)
#endif

using namespace std;
using namespace mongo;

int connect_mongo(DBClientConnection* conn, const string& ip, const string& port)
{ 
    try{
        if( conn->getServerAddress().empty() ){   // not init
            string errmsg;
            if( ! conn->connect( ip  + ":" + port , errmsg ) ){
                printf("FAIL connect mongo, %s", errmsg.c_str());
                return -1;
            }
        }

        if (conn->isFailed()) {
            string errmsg;
            if ( ! conn->connect( ip  + ":" + port , errmsg ) ) {
                printf("FAIL connect mongo, %s", errmsg.c_str());
                return -1;
            }
        }
    }
    catch( DBException& e ) {
        printf("MONGO Exception(connect): %s", e.what());
        return -1;
    }
    catch ( std::exception& e ) {  
        printf("MONGO Exception(connect): %s", e.what());
        return -1;
    }
    catch( ... ){
        printf("MONGO Exception(connect): NULL");
        return -1;
    }

    return 0;
}

int set_mongo(DBClientConnection* conn, const string& dbname, const string& id, const string& value)
{
    try{
        mongo::BSONObjBuilder b;
        long long curtime = time(NULL);
        Date_t date( (curtime - curtime % (3600*24) + ( random() % 6 + 2) * 3600) * 1000 ); // limit ttl deleting time to 2:00-8:00. 

        b.append( "_id", id );
        b.append( "value", value);
        b.append( "ts", date);

        //cout<< b.obj() << endl;
        conn->update( dbname , BSONObjBuilder().append( "_id" , id ).obj(), b.obj(), true );
    }
    catch( DBException& e ) {
        printf("MONGO Exception(set): %s", e.what());
        return -1;
    }
    catch ( std::exception& e ) {  
        printf("MONGO Exception(set): %s", e.what());
        return -1;
    }
    catch( ... ){
        printf("MONGO Exception(set): NULL");
        return -1;
    }

    return 0;
}

int get_mongo(DBClientConnection* conn, const string& dbname, const string& id, string& value)
{
    try{
        BSONObj obj = conn->findOne( dbname, BSONObjBuilder().append( "_id" , id ).obj()); 
        if( !obj.isEmpty() ){
            value = obj.getStringField("value");
        }
    }
    catch( DBException& e ) {
        printf("MONGO Exception(get): %s", e.what());
        return -1;
    }
    catch ( std::exception& e ) {  
        printf("MONGO Exception(get): %s", e.what());
        return -1;
    }
    catch( ... ){
        printf("MONGO Exception(get): NULL");
        return -1;
    }

    return 0;
}

int mget_mongo(DBClientConnection* conn, const string& dbname, const vector<string>& ids, vector<string>& values)
{
    try{
        mongo::BSONObjBuilder b;
        b.append( "$in",  ids);

        auto_ptr<DBClientCursor> cursor = conn->query( dbname, BSON( "_id" << b.obj() ));
        while ( cursor->get() && cursor->more() ) {
            BSONObj obj = cursor->next();

            if( !obj.isEmpty() ){
                values.push_back(obj.getStringField("value"));
            }
        }
    }
    catch( DBException& e ) {
        printf("MONGO Exception(get): %s", e.what());
        return -1;
    }
    catch ( std::exception& e ) {  
        printf("MONGO Exception(get): %s", e.what());
        return -1;
    }
    catch( ... ){
        printf("MONGO Exception(get): NULL");
        return -1;
    }

    return 0;
}

int del_mongo(DBClientConnection* conn, const string& dbname, const string& id)
{
    try{
        conn->remove( dbname, BSONObjBuilder().append( "_id" , id ).obj()); 
    }
    catch( DBException& e ) {
        printf("MONGO Exception(del): %s", e.what());
        return -1;
    }
    catch ( std::exception& e ) {  
        printf("MONGO Exception(del): %s", e.what());
        return -1;
    }
    catch( ... ){
        printf("MONGO Exception(del): NULL");
        return -1;
    }

    return 0;
}

void Print(DBClientConnection& conn, const string& dbname)
{
    auto_ptr<DBClientCursor> cursor = conn.query( dbname , BSONObj() );
    int count = 0;
    while ( cursor->more() ) {
        count++;
        BSONObj obj = cursor->next();
        std::cout<< obj << std::endl;
    }
}

int main( int argc, const char **argv ) 
{
    const char *port = "27000";
    string host( "127.0.0.1" );
    if ( argc < 3 ) {
        std::cout << argv[0] << " dbname host [port]" << endl;
        return EXIT_FAILURE;
    }

    const char* dbname = argv[1];

    if( argc >= 3){
        host = string(argv[2]);
    }
    if( argc >= 4){
        port = argv[3];
    }

    {
        DBClientConnection conn( false , 0 , 2 );
        if( connect_mongo(&conn, host, port) != 0)
        {
            exit(-1);
        }

        string id = "test123";
        string value = "test456";
        del_mongo(&conn, dbname, id);
        set_mongo(&conn, dbname, id, value);

        string ret_val;
        get_mongo(&conn, dbname, id, ret_val);
        if( value != ret_val){
            cout<<"TEST FAIL: " << value << " : " << ret_val <<endl;
        }
    }

    cout << "test finished!" << endl;
    return EXIT_SUCCESS;
}
复制代码
本文转自 zhenjing 博客园博客,原文链接:  http://www.cnblogs.com/zhenjing/archive/2013/04/25/mongodb.html   ,如需转载请自行联系原作者
相关文章
|
分布式计算 关系型数据库 MySQL
将一个电子表格迁移到MySQL和Spark2.0.1上
在这篇简短的指导中,笔者将会简短地回顾一种方法并且用我喜欢的数据集来演示。这不是一个ML库也不是一个Kaggle竞赛的数据集,仅仅是积累了数十年笔者跟踪塑料模型集合产生的数据,如此这般一定会适合传统的标准。
4455 0
|
18天前
|
存储 弹性计算 人工智能
【2025云栖精华内容】 打造持续领先,全球覆盖的澎湃算力底座——通用计算产品发布与行业实践专场回顾
2025年9月24日,阿里云弹性计算团队多位产品、技术专家及服务器团队技术专家共同在【2025云栖大会】现场带来了《通用计算产品发布与行业实践》的专场论坛,本论坛聚焦弹性计算多款通用算力产品发布。同时,ECS云服务器安全能力、资源售卖模式、计算AI助手等用户体验关键环节也宣布升级,让用云更简单、更智能。海尔三翼鸟云服务负责人刘建锋先生作为特邀嘉宾,莅临现场分享了关于阿里云ECS g9i推动AIoT平台的场景落地实践。
【2025云栖精华内容】 打造持续领先,全球覆盖的澎湃算力底座——通用计算产品发布与行业实践专场回顾
|
10天前
|
云安全 人工智能 安全
Dify平台集成阿里云AI安全护栏,构建AI Runtime安全防线
阿里云 AI 安全护栏加入Dify平台,打造可信赖的 AI
|
13天前
|
人工智能 运维 Java
Spring AI Alibaba Admin 开源!以数据为中心的 Agent 开发平台
Spring AI Alibaba Admin 正式发布!一站式实现 Prompt 管理、动态热更新、评测集构建、自动化评估与全链路可观测,助力企业高效构建可信赖的 AI Agent 应用。开源共建,现已上线!
1105 39
|
12天前
|
机器学习/深度学习 人工智能 搜索推荐
万字长文深度解析最新Deep Research技术:前沿架构、核心技术与未来展望
近期发生了什么自 2025 年 2 月 OpenAI 正式发布Deep Research以来,深度研究/深度搜索(Deep Research / Deep Search)正在成为信息检索与知识工作的全新范式:系统以多步推理驱动大规模联网检索、跨源证据。
878 57
|
10天前
|
文字识别 测试技术 开发者
Qwen3-VL新成员 2B、32B来啦!更适合开发者体质
Qwen3-VL家族重磅推出2B与32B双版本,轻量高效与超强推理兼备,一模型通吃多模态与纯文本任务!
728 11
|
4天前
|
人工智能 数据可视化 Java
Spring AI Alibaba、Dify、LangGraph 与 LangChain 综合对比分析报告
本报告对比Spring AI Alibaba、Dify、LangGraph与LangChain四大AI开发框架,涵盖架构、性能、生态及适用场景。数据截至2025年10月,基于公开资料分析,实际发展可能随技术演进调整。
311 4