Tutorial

pick_place_tutorial.cpp pick_place_tutorial.cpp // ROS #include <ros/ros.h> // MoveIt! #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <moveit/move_group_interface/move_group... 阅读详情

Tutorial

Andrew C. Morrow edited this page on 18 May 2015 ·  40 revisions

Getting started with the Legacy C++ Driver

This is an introduction to usage of the MongoDB database from a C++ program.

NOTE: this tutorial is for the legacy and 26compat versions of the C++ driver.

First, install MongoDB – see the installation page for details.

Next, you may wish to take a look at the MongoDB Manual for a language independent look at how to use MongoDB. Also, we suggest some basic familiarity with the mongo shell – the shell is the primary database administration tool and is useful for manually inspecting the contents of a database after your C++ program runs.

Installing the Driver Library and Headers

Please see download and compile page for instructions on how to download, build, and install the C++ client driver.

Initializing the Driver Library

Please see the following wiki pages for instructions on how to properly initialize and terminate the driver:

Connecting

DBClientConnection

The C++ driver includes several classes for managing collections under the parent classDBClientInterface.

  • DBClientConnection is the connection class for connecting to a single MongoDB database server (or mongos)
  • DBClientReplicaSet is the connection class for connecting to a replica set.

See the API documentation for details on each of the above classes.

A simple program that connects to the database
#include <cstdlib>
#include <iostream>
#include "mongo/client/dbclient.h" // for the driver

void run() {
  mongo::DBClientConnection c;
  c.connect("localhost");
}

int main() {
    mongo::client::initialize();
    try {
        run();
        std::cout << "connected ok" << std::endl;
    } catch( const mongo::DBException &e ) {
        std::cout << "caught " << e.what() << std::endl;
    }
    return EXIT_SUCCESS;
}

(Note that in a production environment, the return value of mongo::client::initialize() must be checked)

If you are using gcc on Linux, you would compile with something like this, depending on location of your include files and libraries:

$ g++ tutorial.cpp -pthread -lmongoclient -lboost_thread-mt -lboost_system -lboost_regex -o tutorial
$ ./tutorial
connected ok

Warning

  • Since the tutorial program attempts to connect to a MongoDB database server, you must start it by running mongod before running the tutorial.
  • You may need to append -mt to boost_filesystem and boost_program_options. If using a recent boost, -mt is not needed anymore.
  • You may need to use -I and -L to specify the locations of your mongo and boost headers and libraries.
  • If using the 26compat branch you need to additionally specify -lboost_filesystem and -lboost_program_options

BSON

The MongoDB database stores data in BSON format. BSON is a binary object format that is JSON-like in terms of the data which can be stored (some extensions exist, for example, a Date datatype).

To save data in the database we must create objects of class BSONObj. The components of a BSONObj are represented as BSONElement objects. We use BSONObjBuilder to make BSON objects, and BSONObjIterator to enumerate BSON objects.

The C++ BSON Library

Include bson/bson.h in your application. See bsondemo for example usage.

Key classes
mongo::BSONObj: a BSON object
mongo::BSONElement: a single element in a BSON object. This is a key and a value.
mongo::BSONObjBuilder: used to make BSON objects
mongo::BSONObjIterator: used to enumerate BSON objects
Working with BSON

Let’s now create a BSON “person” object which contains name and age. We might invoke:

BSONObjBuilder b;
b.append("name", "Joe");
b.append("age", 33);
BSONObj p = b.obj();

Or more concisely:

BSONObj p = BSONObjBuilder().append("name", "Joe").append("age", 33).obj();

We can also create BSON objects using the stream oriented syntax:

BSONObjBuilder b;
b << "name" << "Joe" << "age" << 33;
BSONObj p = b.obj();

The BSON Macro lets us be even more compact:

BSONObj p = BSON( "name" << "Joe" << "age" << 33 );

Use the GENOID helper to add an object id to your object. The server will add an _id automatically if it is not included explicitly.

BSONObj p = BSON( GENOID << "name" << "Joe" << "age" << 33 );
// result is: { _id : ..., name : "Joe", age : 33 }

GENOID should be at the beginning of the generated object. We can do something similar with the non-stream builder syntax:

BSONObj p = BSONObjBuilder().genOID().append("name","Joe").append("age",33).obj();

Other helpers are listed BSON Helpers.

Inserting

We now save our person object in a persons collection in the database:

c.insert("tutorial.persons", p);

The first parameter to insert is the namespace. tutorial is the database and persons is the collection name.

getLastError

In order to ensure the write succeeded we need to call getLastError.

Get error result from the last operation on this connection:

string mongo::DBClientWithCommands::getLastError(); // Empty string if no error

Get the full last error object:

BSONObj DBClientWithCommands::getLastErrorDetailed();

For an example, see this demo.

For additional background information on getLastError see the write operations documentation.

Count

Let’s now fetch all objects from the persons collection, and display them. We’ll also show here how to use count().

cout << "count:" << c.count("tutorial.persons") << endl;

Query

auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", BSONObj());

while (cursor->more())
   cout << cursor->next().toString() << endl;

BSONObj() is an empty BSON object – it represents {} which indicates an empty query pattern (an empty query is a query for all objects).

We use BSONObj::toString() above to print out information about each object retrieved.BSONObj::toString is a diagnostic function which prints an abbreviated JSON string representation of the object. For full JSON output, use BSONObj::jsonString.

Let’s now write a function which prints out the name (only) of all persons in the collection whose age is a given value:

void printIfAge(DBClientConnection& c, int age) {
    auto_ptr<DBClientCursor> cursor =
        c.query("tutorial.persons", MONGO_QUERY("age" << age));
    while (cursor->more()) {
        BSONObj p = cursor->next();
        cout << p.getStringField("name") << endl;
    }
}

getStringField() is a helper that assumes the name field is of type string. To manipulate an element in a more generic fashion we can retrieve the particular BSONElement from the enclosing object:

BSONElement name = p["name"];
// or:
BSONElement name = p.getField("name");

See the api docs, and jsobj.h, for more information.

Our query above, written as JSON, is of the form

{ age : <agevalue> }

Queries are BSON objects of a particular format – in fact, we could have used the BSON() macro above instead of MONGO_QUERY(). See class Query in dbclient.h for more information on Query objects, and the Sorting section below.

In the mongo shell (which uses javascript), we could invoke:

use tutorial;
db.persons.find({age : 33});

Indexing

Let’s suppose we want to have an index on age so that our queries are fast. We would use:

c.createIndex("tutorial.persons", fromjson("{age:1}"));

In the above example we use a new function, fromjson. fromjson converts a JSON string to a BSONObj. This is sometimes a convenient way to specify BSON. Alternatively, we could have written:

c.createIndex("tutorial.persons", BSON( "age" << 1 ));

While calling createIndex multiple times won't result in duplicate index creation on the server, it will cause an extra network round-trip and server operation for each call. It's best practice to use this method sparingly, for example once at the beginning of your code, or perhaps in an external setup script that configures the database for your application. For more information about indexing, see theMongoDB Indexing docs.

Sorting

Let’s now make the results from printIfAge sorted alphabetically by name. To do this, we change the query statement from:

auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", MONGO_QUERY("age" << age));

to

auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", MONGO_QUERY("age" << age ).sort("name"));

Here we have used Query::sort() to add a modifier to our query expression for sorting.

Updating

Use the update() method to perform a database update. For example the following update in the mongo shell:

> use tutorial
> db.persons.update( 
    { name : 'Joe', age : 33 },
    { $inc : { visits : 1 } }
)

is equivalent to the following C++ code:

db.update("tutorial.persons",
    BSON("name" << "Joe" << "age" << 33),
    BSON("$inc" << BSON( "visits" << 1))
);

The update() method can be used to modify specific fields, replace the entire existing document, insert new documents or update multiple documents. In the MongoDB Manual, examples are provided in the Modify Documents Tutorial.

Arrays

A simple example illustrating usage of BSON arrays and the $nin operator is available here.

Further Reading

This overview just touches on the basics of using MongoDB from C++. There are many more capabilities. For further exploration:

在ROS2运行urdf_tutorial例程 文章目录前言一、安装依赖库二、下载源代码三、编译源代码四、运行urdf_tutorial功能包例程五、参考文献 前言 在参考ROS2的官方教程学习urdf时,运行urdf_tutorial的例程很容易会因为一些依赖的库没有安装遇到问题,这里记录一下我踩坑之后总结的过程。 一、安装依赖库 这里得先说一下,我的ROS2的版本(distro)是foxy。首先我们得安装urdf_tutorial里面用到的一些库,不然在运行里面的文件的时候会出问题。我们需要安装joint-state-publisher-gui,j 阅读详情

相关推荐

move_group_interface_tutorial.cpp

move_group_interface_tutorial.cpp #include <moveit/move_group_interface/move_group_interface.h> #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <moveit...

RealMadridCF 1万+

C++tutorial(一)

编译器 遵循这些教程所需的基本工具是计算机和编译器工具链,它们能够编译C ++代码并构建在其上运行的程序。 C ++是一种多年来发展很快的语言,这些教程解释了最近添加到该语言的许多功能。因此,为了正确地遵循教程,需要最近的编译器。它应支持(即使只是部分)2011标准引入的功能。 许多编译器供应商在不同程度上支持新功能。有关已知支持所需功能的某些编译器,请参见本页底部。其中一些是免费的! 如果由于某...

IQIT 559

【Kaggle Tutorial的使用】

什么是Kaggle?Kaggle允许你在线编写和执行Python代码无需配置免费使用GPU(每周30小时)轻松共享更强的GPU资源上传数据集,举办竞赛…

zzzyyy8的博客 872

openGL4.3 G++ 编译命令

g++ tutorial01.cpp  -o tutorial01.o -rdynamic -lGLU -lGL /usr/local/lib/libglfw3.a /usr/local/lib/libGLEW.a -lGLU -lGL -lGLU -lXrandr -lXext -lX11 -lrt -ldl -lrt -lm -lX11 -lpthread -lXrandr -lXineram...

thomasyuan8的专栏 1038

《ParaView Tutorial》

看到这篇博客的小伙伴大家好,在这里主要是想发布一则信息: 《ParaView Tutorial》系列图文教程上线了。 写本教程的起因 首先说一下写这一系列教程的原因,主要有三个。首先,起因是很多小伙伴给我发私信和邮件求助,可能这些同学都是初次接触ParaView,所以咨询的大多数问题都很基础。而要解释清楚这些基础问题需要很大的篇幅,所以有时很难帮到他们。其次,目前没有较好的中文资料来学习ParaView,官方的文档是英文的,对初次接触的用户也不太友好,而网上关于ParaView的介绍也很零散.

黄岛主的博客 1万+

【Unity 实用工具篇】✨ | Tutorial Master 2 游戏引导教程 功能深入学习

新手教程是大部分游戏都会有的一个需求,可以帮助玩家更快的上手游戏,避免被不懂操作而被开局就劝退。 Tutorial Master 2 是一个编辑器扩展插件,创建游戏互动教程会非常的快速和容易! 前面写了一篇文章讲了怎样快速创建一个引导教程,那本篇文章就来深入学习下关于Tutorial Master 的更多知识。

努力前行,总会成为自己心中的那道光 1万+

Tutorial 03_分布式数据库HBASE

(一)编程实现一下内容,并用Hadoop提供的Shell命令完成相同任务: 编程实现: (1)列出HBase所有表的相关信息,例如表名; package tutorial01; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hba...

weixin_30702887的博客 114

是德频谱分析仪相位噪声测量实战指南:从原理到精准操作

本文详细介绍了是德频谱分析仪在相位噪声测量中的实战操作指南,从基础概念到高级技巧全面解析。通过5G基站时钟测量等实际案例,展示如何利用是德N9030B等设备精准测量相位噪声,并分享设备预热、参数设置、环境干扰排除等关键操作要点,帮助工程师提升测量精度和效率。

jenkins8butler的博客 243

django-rest-framework Tutorial

Tutorial https://www.django-rest-framework.org/tutorial/1-serialization/ 翻译: https://darkcooking.gitbooks.io/django-rest-framework-cn/content/chapter1.html https://q1mi.github.io/Django-REST-framework...

abc 232

别再瞎猜了!Fluent瞬态计算时间步长到底设多少?一个公式+实战案例搞定

本文详细解析了Fluent瞬态计算中时间步长的设置方法,通过黄金公式和实战案例,帮助工程师准确确定时间步长,避免计算发散和资源浪费。文章还介绍了动态调整策略和典型工程场景的参数优化,提升仿真效率和精度。

weixin_42638178的博客 435

SAP CO实战:如何用KKA2/CJ88结果分析码搞定项目收入成本匹配(附真实案例)

本文深入探讨了SAP CO模块中KKA2和CJ88结果分析码在项目收入成本匹配中的高阶应用。通过真实案例解析,详细介绍了这两种分析码在分阶段收入确认和终验法项目中的配置技巧与实战经验,帮助财务人员高效解决复杂业务场景下的财务数据处理难题。

weixin_29230773的博客 187

FreeSurfer Tutorial Datasets训练数据配置

    1、下载数据 如下命令实现下载实验数据,大概8GB,并解压建立一个文件夹tutorial_data。最后清除下载包。 curl https://surfer.nmr.mgh.harvard.edu/pub/data/tutorial_data.tar.gz -o tutorial_data.tar.gz tar -xzvf tutorial_data.tar.gz rm tuto...

qimo601的专栏 977

【MDC开发者课程】MDC功能软件-归控算法介绍

规控算法

博客标题不能为空我也没办法 1849

【Colab Tutorial的使用】

什么是Colab 或者 Colaboratory?Colaboratory 是一个 Google 研究项目,旨在帮助传播机器学习培训和研究成果。它是一个 Jupyter 笔记本环境,不需要进行任何设置就可以使用,并且完全在云端运行。Colaboratory 笔记本存储在 Google 云端硬盘中,并且可以共享,就如同您使用 Google 文档或表格一样。Colaboratory 可免费使用。

zzzyyy8的博客 1549

LAMMPS实例教程—In文件详解

本博文主要介绍专栏 《LAMMPS实例教程—In文件详解》, 针对于 Lammps 可分析的物理过程进行讲解,提供 In 文件以及后处理方法,持续更新。 目前分为8个专题: 1)力学专题、2)传热专题、3)相变专题、4)界面专题、5)吸附专题、6)流动专题、7)物性专题以及8)基础理论专题。

Rockyoung 3万+

pytest学习和使用19-pytest断言失败后,怎样保持后续的断言继续执行?(pytest-assume)

【代码】pytest学习和使用19-pytes断言失败后,怎样保持后续的断言继续执行?

虫无涯的博客 1396

guide, manual, tutorial之间的区别

总结:一般而言,guide表示用户指南,提供简要的信息;manual表示用户手册,提供较为完整深入的说明;tutorial表示教程,提供详细的说明,侧重于给没有经验的人一步一步进行详细的指导。实际情况中,guide和manual常混用。 以下译自网络,感谢解答问题的native speaker :P Difference between user guide and user man...

weixin_30814319的博客 4182

数据本体论如何指导数仓建模?

数据本体论指导数仓建模的核心在于构建业务语义与数据结构的桥梁。该方法从业务域中抽象标准化知识体系,包含核心概念、属性、关系和规则五大要素,并将其映射为分层数仓模型。通过"业务本体梳理→本体建模→模型映射→治理迭代"的流程,实现数仓从"结构存储"到"语义载体"的升级。相比传统建模,该方法能解决语义不一致、跨域融合难等问题,使数仓具备更好的可扩展性和业务对齐性。实践表明,以数据本体论为指导的数仓建模能显著提升数据资产的可理解性和复用价值。

石榴姐yyds 404

visualizing_collisions_tutorial.cpp

visualizing_collisions_tutorial.cpp #include <ros/ros.h> #include "interactivity/interactive_robot.h" #include "interactivity/pose_string.h" // MoveIt! #include <moveit/robot_model/robot_...

RealMadridCF 1万+

不得不懂的代理选型指南

背景:在项目实战中,生产者成功率从 05-15 的 43.6% 崩塌到 9.7%~11.8%,根因是 KDL 隧道代理单 IP 被 Kasada 烧穿。本文记录代理选型分析与推荐。

youbingchen的博客 398

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

TUTORIAL:快速掌握 SimpleITK 的核心功能与场景

TUTORIAL:快速掌握 SimpleITK 的核心功能与场景 项目介绍 SimpleITK 是一个开源的医学图像处理库,它基于 ITK (Insight Segmentation and Registration Toolkit) 开发,旨在为研究人员和开发者提供一个简单易用的工具包。TUTORIAL 是 SimpleITK 的官方教程,它提供了详细的指导和丰富的示例,帮助用户快速学习和掌握 ...

gitblog_00967的博客 708

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

planning_scene_ros_api_tutorial.cpp

planning_scene_ros_api_tutorial.cpp #include <ros/ros.h> #include <geometry_msgs/Pose.h> // MoveIt! #include <moveit_msgs/PlanningScene.h> #include <moveit_msgs/AttachedCollis...

RealMadridCF 1万+

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

如何运行一个CFDEM tutorial case

新手入门 万里长征第一步, 安装完CFDEM后, 我们知道有很多tutorial可以教我们怎么设置合理的参数. 很多tutorial case里都有写好的Allrun脚本, 最简单的方法就是运行Allrun脚本走一遍流程 准备工作 复制随便一个tutorial到用户自己的run文件夹, 比如 cp -r $CFDEM_PROJECT_DIR/tutorials/cfdemSolverPiso/...

beidou111的博客 4306

muduo-tutorial

muduo-tutorial 是一个面向 C++ 开发者的教程,它介绍了如何使用 muduo 库进行网络编程。muduo 库是一个高效的、开源的 C++ 网络库,它提供了多线程支持、事件驱动模型等功能,可以用于开发高性能的服务器应用。 使用场景 muduo-tutorial 教程可以帮助开发者了解如何使用 muduo 库实现以下功能: 建立异步网络服务器:通过使用 muduo 库提供的事件驱动模...

gitblog_00082的博客 544

Lecture、Seminar、Tutorial、Workshop

无非是看一下你的功课是否你做的,假如是小组功课的话,看你是否介入了,当然只要事先筹备充分,绝对没问题。普通的来讲便是我们海内所讲的功课,只是这个功课一样平常常常是要被评分并且被记录进你这门课的总评分的,一样平常占总分的10%-50%。有些是你的论文导师或者是任课师长教师,可以和你评论争论论文或者是功课。这个一样平常只在文科中呈现,便是几个同砚合营演一个场景(戏),按照师长教师的要求,对一个特定的主题,表现自己的设法主见和处置惩罚要领。而且英国也是有口音存在的,语速每每也很快,以是这也是对听力的一种磨练,

wangprince2017 2325

Vue Tutorial 项目指南

Vue Tutorial 项目指南 本指南旨在详细介绍位于 https://github.com/taniarascia/vue-tutorial.git 的 Vue.js 教程项目,帮助开发者快速理解其结构、启动方式以及关键配置。 1. 项目目录结构及介绍 Vue Tutorial 项目通常遵循标准的 Vue.js 应用结构,但具体结构可能会基于作者的设计有所变化。以下是一个典型的Vue项目结构...

gitblog_00201的博客 958
上一篇: windows下使用Cmake和VC 2013安装mongodb C driver Windows下安装mongodb的C语言程序驱动必须借助交叉编译软件CMake,但是官网上的文档对于一些
下一篇: mongodb c driver的使用总结(1)
linuxheik
博客等级 码龄15年 865粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址