随笔 - 79  文章 - 58  trackbacks - 0
<2015年3月>
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

常用链接

留言簿(9)

随笔分类

随笔档案

文章档案

相册

搜索

  •  

积分与排名

  • 积分 - 291746
  • 排名 - 87

最新评论

阅读排行榜

评论排行榜

1、查询样例

bson_t query;
bson_t child;
bson_init(&query);

BSON_APPEND_INT64(&query, "id", 0);

mongoc_cursor_t m_pCursor = mongoc_collection_find(m_pCollection,
    MONGOC_QUERY_NONE,
    0,
    0,
    0,
    &query,
    NULL,  /* Fields, NULL for all. */
    NULL); /* Read Prefs, NULL for default */

bson_destroy(&query);
bson_error_t error;
if (mongoc_cursor_error(m_pCursor, &error)) {
    cout << "Query Failure: " << error.message;
    return;
}

const bson_t *doc;

while (!mongoc_cursor_error(m_pCursor, &error)
    && mongoc_cursor_more(m_pCursor))
{
    if (mongoc_cursor_next(m_pCursor, &doc))
    {
        GetRecord(doc);
    }
    else
    {
        break;
    }
}
if (mongoc_cursor_error(m_pCursor, &error)) {
    cout << "Query Failure: " << error.message;
}

mongoc_cursor_destroy(m_pCursor);

2、获取记录

void GetRecord(const bson_t *doc)
{
    bson_iter_t iter;
    bson_iter_init(&iter, doc);

    if (bson_iter_find(&iter, "id"))
    {
        cout << bson_iter_int64(&iter) << "|";
    }
   
    if (bson_iter_find(&iter, "field1"))
    {
        cout << bson_iter_int64(&iter) << "|";
    }

    if (bson_iter_find(&iter, "field2"))
    {
        const uint8_t *binary = NULL;
        bson_subtype_t subtype = BSON_SUBTYPE_BINARY;
        uint32_t binary_len = 0;
        bson_iter_binary(&iter, &subtype, &binary_len, &binary);
        string msg;
        msg.assign((const char*)binary, binary_len);
        cout << msg << endl;
    }
}

3、复杂的or查询和比较查询

//id==4 or field1 <= 12
bson_t query;
bson_t child, child2, child3;
bson_init(&query);
bson_append_array_begin(&query, "$or", -1, &child);

//0: 第一个or部分
bson_append_document_begin(&child, "0", -1, &child2);
BSON_APPEND_INT64(&child2, "id", 4);
bson_append_document_end(&child, &child2);

//1:第二个or部分
bson_append_document_begin(&child, "1", -1, &child2);

//field1 <= 12
bson_append_document_begin(&child2, "field1", -1, &child3);
BSON_APPEND_INT64(&child3, "$lte", 12);
bson_append_document_end(&child2, &child3);

bson_append_document_end(&child, &child2);

bson_append_array_end(&query, &child);

char * str = bson_as_json(&query, NULL);
printf("\n%s\n", str);
posted on 2014-09-27 16:11 merlinfang 阅读(7373) 评论(2)  编辑 收藏 引用 所属分类: mongodb

FeedBack:
# re: mongodb c driver的使用总结(2)-- 查询[未登录] 2015-03-31 13:37 xxx
//1:第二个or部分
bson_append_document_begin(&child, "1", -1, &child2);
===》》》
bson_append_document_begin(&child, "1", -1, &child3);  回复  更多评论
  
# re: mongodb c driver的使用总结(2)-- 查询 2016-03-28 15:08 aaa
啊啊啊啊啊  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理