MongoDB C++应用 简单例子

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

假定你已经有了MongoDB server,并且工作在Ubuntu上,安装了GCC,下面的C++程序可以帮助你快速进入能够使用MongoDB的状态。

#include <cstdlib>#include <mongo/client/connpool.h>using namespace std;using namespace mongo;void SaveStatus(mongo::DBClientBase& session, string const& display_id, string const& status) {        BSONObjBuilder condition;    condition.append("display_id", mongo::OID(display_id));    BSONObjBuilder status_field;    status_field.append("status", status);    BSONObjBuilder data;    data.append("$set", status_field.obj());    session.update("mydb.mycoll", mongo::Query(condition.obj()), data.obj());}/* *  */int main(int argc, char** argv) {    mongo::ScopedDbConnection con("localhost", 5000);//timeout is 5000    mongo::DBClientBase& session = con.conn();            BSONArrayBuilder display_ids;    display_ids.append(mongo::OID("5061f915e4b045bab5e0c957"));    BSONObjBuilder in_condition;    in_condition.append("$in", display_ids.arr());        BSONObjBuilder message_condition;    message_condition.append("display_id", in_condition.obj());    message_condition.append("status", "sending");        BSONObjBuilder sortBuilder;    sortBuilder.append("_id", 1);    mongo::Query query(message_condition.obj());    mongo::Query query2(query);    mongo::Query query_with_sort(query.sort(sortBuilder.obj()));    BSONObjBuilder update_field;    update_field.append("status", "waiting");    BSONObjBuilder set_field;    set_field.append("$set", update_field.obj());    session.update("mydb.mycoll", query2, set_field.obj(), false, true);            con.done();    return 0;}


提示:

1.SaveStatus函数内部演示了简单的设置某个字段值的用法。

2.main函数中演示了更加复杂的用法,用$in作为update语句的查询条件。

3.最后的con.done()函数调用是必须的,因为连接必须回到池中。

4.session.update的查询条件不能带sort,否则更新不会成功,因此可以看到我的代码中专门复制了一个query2对象用于update, 而query_with_sort 可以用于一般的查询(find)。

5.BSONObject的obj方法只能被调用一次,第二次程序就会crash。

6.mongo::OID用来将字符串转换成OID对象,也就是常见的_id的值

7.有时候当碰到编译错误的时候,可以试一下这个头文件:

#include "mongo/client/dbclient.h"



           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值