MongoDB C++ Tutorial

Windows下MongoDB 4.0.28实战部署教程 MongoDB是一种面向文档的NoSQL数据库,其核心原理是通过BSON格式存储灵活的JSON-like数据,并依赖mongod服务进程提供持久化与查询能力。在Windows平台,技术价值突出体现在轻量部署、免运维依赖及高校实训高兼容性上——尤其MongoDB 4.0.28作为最后一个功能完整的免费社区版,对Visual C++运行库和Windows服务机制有明确要求,成为头歌等教学平台的事实标准。典型应用场景包括学生信息管理、本地开发环境搭建及Java/Python后端数据接入。本文聚焦Windows环境 阅读详情

MongoDB C++ Tutorial

We will learn about the basics of MongoDB C++ leagcy driver here and how to implement it

Connecting to MongoDB

  1. Normal Connection (Without Password)

    mongo::DBClientConnection conn;

    Mongo::Status status = mongo::client::initialize()

    if (!status.isOK()) {

    MongoException m(-1, “failed to initialize the client driver: ” + status.toString());

    return -1

    }

    string url = “localhost:27017”;

    if (!conn.connect(url, errmsg)) {

    MongoException m(0, “couldn’t connect : ” + errmsg);

    return -1;

    }

    This will establish a normal connection with MongoDB i.e. without performing any authentication work.

  2. Authentication

    conn.auth(BSON(

    “user” << “root” <<

    “db” << “mydatabase” <<

    “pwd” << “password” <<

    “mechanism” << “DEFAULT”

    ));

    You need to change the values passed to the function conn.auth according to your setup of MongoDB

Fetching rows from the collection

Suppose you have a collection with the following fields:

  1. timestamp
  2. date
  3. time
  4. latitude
  5. longitude
  6. speed
  7. direction

Making Query

Let us evaluate different conditions to make the Query object. MONGO_QUERY is a helper macro used for creating the Query object.

Case 1:

timestamp > 142400000 and timestamp < 142500000

mongo::Query b = MONGO_QUERY(“timestamp” << mongo::GT << (long long) 142400000 << “timestamp” << mongo::LT << (long long) 142500000);

Case 2:

timestamp > 142400000 and timestamp < 142500000

Sorted in ascending order

mongo::Query b = MONGO_QUERY(“timestamp” << mongo::GT << (long long) 142400000 << “timestamp” << mongo::LT << (long long) 142500000);

b.sort(“timestamp”,1)

Case 3:

timestamp > 142400000 and timestamp < 142500000

Sorted in descending order

mongo::Query b = MONGO_QUERY(“timestamp” << mongo::GT << (long long) 142400000 << “timestamp” << mongo::LT << (long long) 142500000);

b.sort(“timestamp”, -1)

Matching binary data

string tag = “Binary”;

mongo::BSONBinData be((void *) tag.c_str(), tag.length(), mongo::BinDataGeneral);

mongo::Query b = MONGO_QUERY(“description” << be);

Matching with all the parameters having speed 0

string tag = “Binary”;

mongo::BSONBinData be((void *) tag.c_str(), tag.length(), mongo::BinDataGeneral);

mongo::Query b = MONGO_QUERY(“timestamp” << mongo::GT << (long long) 142400000 << “timestamp” << mongo::LT << (long long) 142500000 <<“speed” << “0” << “description” << be);

b.sort(“timestamp”, 1);

Above query simply means that timestamp > 142400000 and timestamp < 142500000, speed = 0 and description having binary data equivalent to “Binary”. BSONBinData is the Object that is required to be passed to the MONGO_QUERY macro for performing the comparison.

Executing Query

Now we have made the connection and the query, next we will execute this query on the server. In this we shall be using the database “mydb” and collection name “Locations”

string collectionName = “mydb.Locations”

auto_ptr<mongo::DBClientCursor> cursor = conn.query(collectionName,b);

mongo::BSONObj p;

while (cursor->more()) {

p = cursor->next();

// Do something with the fetched record

}

We now declare a cursor variable which will return pointer to the records formatted in the BSONObj format. cursor->more() checks if we have any more rows to be retrieved from the server and if yes we call cursor->next() which returns BSONObj object.

Retrieving N records only

auto_ptr<mongo::DBClientCursor> cursor = conn.query(collectionName,b, 10);

In order to retrieve N number of records we can pass additional parameter to the query function with number of records required to be fetched from the server. This is equivalent to the LIMIT clause in WHERE statement of SQL

Data Retrieval from BSONObj

Finally we are required to retrieve various fields from the BSONObj given by the cursor->next()

string collectionName = “mydb.Locations”

auto_ptr<mongo::DBClientCursor> cursor = conn.query(collectionName,b);

mongo::BSONObj p;

while (cursor->more()) {

p = cursor->next();

// Do something with the fetched record

double latitude = p.getField(“latitude”).Double();

double longitude = p.getField(“longitude”).Double();

}

In the above case we always assume that the data is inserted in the Double format inside the collection. Sometimes it becomes necessary to evaluate the type and perform conversion as per your requirement. We can achieve it with the following code

double latitude;

while (cursor->more()) {

p = cursor->next();

// Do something with the fetched record

switch (p.getField(“latitude”)) {

case mongo::NumberDouble:

latitude = p.getField(“latitude”).Double();

break;

case mongo::String:

{

string lat = p.getField(“latitude”).String();

sscanf (lat.c_str(), “%lf”, &latitude);

}

break;

}

}

Count

Counting number of records present in the collection

cout << “count:” << conn.count(“mydb.Locations”) << endl;

Insert Rows into collection

Inserting rows into MongoDB required usage of BSONObjBuilder. Following code will illustrate on addition of 4 fields in the object and then inserting it into the collection

//Create BSONObjBuilder type Object

obj = new mongo::BSONObjBuilder();

//Append various fields and set their values

obj->append(“latitude”, 27.24424);

obj->append(“longitude”, 78.24242);

obj->append(“speed”, 0);

obj-appendBinData(“description”, 6, mongo::BinDataGeneral, “Binary”);

//Perform insertion command

conn.insert(dbCollection, obj->obj());

std::string e = conn.getLastError();

if (!e.empty()) {

MongoException m(1, “insert failed: ” + e);

return -1;

}

Indexing

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

conn.createIndex(“mydb.Locations”, fromjson(“{timestamp: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:

conn.createIndex(“mydb.Locations”, BSON( “timestamp” << 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.

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.

Leave a Reply

MongoDB Windows实战:安装、权限与聚合查询全打通 MongoDB 是一种以文档为中心的非关系型数据库,其核心在于灵活的数据模型与无预定义 Schema 的设计逻辑。不同于 SQL 数据库的表结构与外键约束,MongoDB 依赖嵌套文档、引用关系和聚合管道实现数据操作。掌握其在 Windows 环境下的本地部署(含 vcruntime140.dll 依赖与 NT SERVICE\MongoDB 权限配置)、基于 authSource=admin 的权限体系构建,以及将业务需求(如‘查高分选课学生’)精准映射为 $elemMatch、$lookup 和 $gr 阅读详情

相关推荐

MongoDB C/C++开发使用案例Demo

MongoDB C/C++开发使用案例Demo(含源代码例子、编译好的MongoDB C库文件(.h .lib .dll)、开发环境搭建配置文档等),可直接用于项目开发

C++ 实战Mongodb CRUD操作基本用法

mongo c++ driver crud + 高级操作

weixin_44834554的博客 2847

tutorial-2015mongodb:MongoDB教程,在2015年仓促为COMP391编写

教程wk9:MongoDB 本教程的起点是用户管理教程的解决方案。 在该教程中,我们有一个UserService将用户数据存储在内存中。 在本教程中,我们将其放入数据库中。 由于我们的条款还很晚,解决方案将立即发布-您可以通过比较master分支和solution分支来查看需要做的事情。 我建议您检出master分支,并在遇到困难时偶尔查看github.com上的solution分支。 添加驱动程序 第一步已经为您完成-将数据库驱动程序添加到build.sbt的依赖build.sbt libraryDependencies ++ = Seq ( " org.mindrot " % " jbcrypt " % " 0.3m " , " org.mongodb " % " mongodb-driver " % " 3.0.2 " ) 连接到数据库 在UserService.ja

C++调用MongoDB数据库

C++调用MongoDB数据库(一) 一、简介 本篇文章主要讲述如何使用C++调用MongoDB数据库实现增、删、查、改。 MongoDB MongoDB是一个基于分布式文件存储的数据库,由C++语言编写,一般多用于WEB应用进行可扩展的高性能数据存储。MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。 MongoDB文档 MongoDB中的记录是一个文档,它是由

m0_46185044的博客 7175

汇川EASY521 PLC实战指南:从硬件选型到程序架构与故障排查

可编程逻辑控制器(PLC)是工业自动化系统的核心大脑,其工作原理基于循环扫描机制,持续读取输入、执行用户程序并更新输出。这种确定性控制方式,使其在逻辑控制、顺序控制和运动控制中具有不可替代的技术价值,广泛应用于机械设备、生产线和过程控制等场景。对于汇川EASY521这类紧凑型高性能PLC,其核心优势在于集成了运动控制与丰富通讯接口,为中小型设备提供了高性价比的一站式解决方案。在实际应用中,工程师常需处理如“汇川sv660n”伺服驱动器的集成调试,或利用“hslcommunication”等开源库实现C#上位

weixin_42525264的博客 777

vivado下ECO操作-不重新综合实现修改属性并生成.bit

ECO即engineer change order,即工程变更指令,可以对设计做局部小改动并只对改动部分重新布局布线并生成.bit。在一个工程动辄编译几个小时情况下,可以在调试中节省大量时间。比如我们在调试中,需要改变时钟占空比或者相位,需要改变寄存器初值等等,此时用ECO暂时改动,待验证后在重新编译无疑是最有效率的方法。 实现ECO通常有两种方式,一是通过vivado界面完成,另一种方法就是tcl脚本。所有的ECO操作都可以通过tcl操作完成,有的操作用vivado界面无法完成,只能通过tcl。以下主要

4684

使用C++进行MongoDB操作

它接受一个集合名称和一个聚合管道(Aggregation Pipeline)作为参数,根据聚合管道的定义,从指定的集合中抽取数据,并生成一个虚拟的文档集合。该函数在插入成功后返回一个InsertOneResult对象,可以通过该对象获取插入的文档的_id值和操作结果等信息。函数是旧版本MongoDB C++驱动程序中的函数,用于将一个或多个文档对象插入到MongoDB数据库中。它接受一个文档对象或文档对象数组作为参数,并将这些文档对象插入到指定的集合中。函数是用于插入单个文档对象的函数,

qq_47258321的博客 1537

Proteus仿真实战:用STM32F103C8T6输入捕获模式精准测量PWM频率(附完整代码)

本文详细解析了如何在Proteus仿真环境中,利用STM32F103C8T6的输入捕获模式精准测量PWM频率。文章从输入捕获的工作原理、Proteus电路搭建、模块化代码实现到调试优化,提供了完整的实战指南和代码示例,帮助开发者深入理解并掌握这一关键技术。

weixin_29158047的博客 261

MongoDB数据库协议解析及C/C++代码实现

MongoDB Wire Protocol是一个简单的基于socket,请求/响应方式的协议,客户端使用常规的TCP/IP套接字(socket)进行通信,服务端默认监听端口是 27017。

chen1415886044的博客 3854

计算机网络(国家电网)

1.局域网中NOS(网络操作系统)提供的通信服务有工作站与工作站之间的对等通信,工作站与服务器之间的通信2.ISP:Internet服务商应用层 APDU(应用层协议数据单元)表示层 PPDU(表示层协议数据单元)会话层 SPDU(会话层协议数据单元)传输层 segment(报文段)网络层 packet (数据包)数据链路层 frame(数据帧)物理层 bit (比特)4.

qq_31715647的博客 3201

【异常】Codybuddy Error Code: 14003 too many requests 限流报错问题排查与解决指南

14003报错本质为服务端限流拦截,并非账号封禁或程序致命故障,90%以上的场景可通过等待冷却+规范使用行为解决。通过本文的排查步骤,可快速恢复工具使用,同时规避后续重复触发该问题。

奶爸的编程之路,也就一周冷个三天 1270

mongodb学习笔记--C++操作mongodb

mongodb学习笔记–C++操作mongodb   学习mongodb过程当中,必须学习的就是用C++(Java、PHP、C#等)操作mongodb,这里讲述C++操作mongodb,在官方提供的mongo-cxx-driver驱动中有相关的操作例子,可以结合例子学习,目录是mongo-cxx-driver-legacy-1.0.0-rc0\src\mongo\client\examples,这里针对几个重要的点。

wonderomg 1万+

桌面实施远程光电体积描记法:使用面部视频测量心率的C++详细指南

在现代医疗和健康监测领域,心率是一个非常重要的生理参数,它可以为我们提供关于身体健康状况的重要信息。但是,随着技术的进步,现在我们有了一种新的方法,称为远程光电体积描记法(rPPG),它可以无需与皮肤接触就测量心率。然后,我们从面部颜色的信号序列中提取绿色通道的值,因为绿色通道对于心率的变化最为敏感。在上述代码中,我们使用了OpenCV库,它是一个开源的计算机视觉库,非常适合这种应用。这种变化是由于血液流动引起的,当心脏跳动时,血液流经面部,导致肤色的轻微变化。要实现rPPG,首先需要检测并跟踪人脸。

qq_38334677的博客 617

MongoDB C++ Tutorial BSONBinData

MongoDB C++ Tutorial We will learn about the basics of MongoDB C++ leagcy driver here and how to implement it Connecting to MongoDB Normal Connection (Without Password

linuxheik的专栏 890

基于CANopen协议,实现机器人500-1000Hz高频控制(附实操实例) (1)

基于CANopen协议实现机器人500-1000Hz高频控制,核心不是“协议本身的性能极限”,而是“通过优化配置、硬件适配、软件调优,最大化发挥协议的实时性优势”。关键在于:以PDO为核心实现实时数据传输,以SYNC帧锁定高频同步周期,以精简冗余、优化硬件降低总线负载,同时通过实操调试解决周期漂移、延迟、干扰等问题。

start_up_go的博客 99

【产品经理修炼之道】-如何搭建企业级账务系统?

笔者公司的业务模式具有一定的独特性,不同于我们常见的市面上供应链类公司的进销存模式。公司主要为各大银行和金融机构提供信贷领域的风控服务,客户主要通过请求公司的数据产品接口产生费用,可以简单地理解为请求一次接口收费0.5元,一个月若是有1w人请求同一个接口则公司需要收费5000元。

xiaoli8748的专栏 5414

MongoDB C++ DRIVER 编译

转自 http://nosql-db.com/topic/51556970ca60a10d420148e4 之前装过,忘了 ,找了篇博客 COPY作记录     MongoDB python和MongoDB c++驱动安装   java 简单,略过。python $ git clone git://github.com/mongodb/mongo-python-driver....

野兽 310

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

C++ 连接Mongo数据库实现增删改差

没人教,没人带,没文档,自己找了资料找了一下午终于写好了,可以当个参考吧,注释不多,浅显易懂。 #include&lt;cstdlib&gt; #include&lt;iostream&gt; #include"mongo/client/dbclient.h" using namespace mongo; DBClientConnection conn; void insert(string ...

hpuzsk的博客 1835

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

MongoDB&C++开发(四)bsoncxx::builder::stream::document的增删改查操作

2. mongocxx 续上一篇,接着看一下mongocxx中的文件有些什么。 先看一下基本的增删改查操作: 2.1 connect.cpp 数据库的链接 参见之前的博客。 2.2 create.cpp 构造文档并插入 构造一个文档,插入数据库中的一个collection。 #include #include #include #include #include

自己的学习笔记 7775

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Tutorial

mongodb/mongo-cxx-driver  Code Pull requests 9 Wiki Pulse Graphs Tutorial Andrew C. Morrow edited this page on 18 May 2015 · 40 revisions  Pages 16 Home

linuxheik的专栏 595

【MongoDB 学习专题(基础篇)】MongoDB 入门

一. MongoDB 介绍 MongoDB 是一个基于分布式文件存储的的开源数据库系统,由 C++ 语言编写,旨在为 WEB 应用提供一个可扩展的、高性数据存储解决方案。它是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最接近于关系数据库的。 MongoDB 将数据存储为一个文档,数据结构由键值 (key=>value) 对组成。MongoDB 中的文档类似于 JSON 对象,字段值可以包含其他文档,数组及文档数组。 二. MongoDB 概念 SQL 术语/概念和 Mo

盛夏温暖流年 1434

MongoDB 文档数据库完全指南:db-tutorial 从零到高手

MongoDB 是一个基于分布式文件存储的文档数据库,由 C++ 语言编写,旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。作为 db-tutorial 项目的核心内容之一,本指南将带你从零开始掌握 MongoDB 的所有关键知识点。 ## 📋 为什么选择 MongoDB? MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于

gitblog_01102的博客 418

MongoDB Java CRUD实战:从环境搭建到高并发避坑指南

MongoDB作为主流文档型数据库,凭借灵活的BSON结构、无Schema约束和原生JSON支持,成为Java微服务中处理非结构化数据的核心选择。其底层基于内存映射文件与WiredTiger存储引擎,兼顾写入吞吐与查询性能;通过副本集实现高可用,借助分片集群支撑水平扩展。在Java生态中,mongodb-driver-sync驱动提供同步API,而Spring Data MongoDB进一步封装了POJO映射、方法名查询与事务管理,显著提升开发效率。典型应用场景包括用户行为日志采集、商品动态属性存储、IoT

weixin_30613727的博客 395

安装 MongoDB、与SQL语法对比、Python (异步)操作 mongodb:增、删、改、查

安装 MongoDB、与SQL语法对比、Python (异步)操作 mongodb:增、删、改、查

freeking101的博客 8725

MongoDB本地安装启动避坑指南:Windows/Linux/macOS全平台实战

MongoDB作为主流文档型数据库,其本地环境部署常因系统差异引发启动失败、连接拒绝、数据丢失等基础问题。核心原理在于不同操作系统对服务注册、动态链接、权限模型和安全机制(如Windows服务账户、Linux glibc ABI兼容性、macOS SIP保护)的底层约束。技术价值体现在保障开发环境稳定可用,支撑IDE、测试框架及脚本的可靠集成。典型应用场景包括前端本地调试、微服务单机验证、教学实训环境搭建及CI/CD流水线初始化。本文聚焦真实生产验证的跨平台启动方案,覆盖Windows权限陷阱、Linux依

weixin_33782386的博客 493

mongodb客户端编程

from : http://blog.csdn.net/fuxingdaima/article/details/8296405 研究了大半天,终于可以在windows的vs2008通过C++编码来实现连接mongodb服务器,从而进行其它数据库存取操作。 一、花这么多时间原因是开始时不懂得这几个东西scons,python,SpiderMonkey, boost与mon

百川 1273
上一篇: mongodb存储二进制数据
下一篇: mongodb二进制操作
linuxheik
博客等级 码龄15年 865粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址