mongodb:带条件查询

主要演示了条件查收:

1)查询条件

2)排序条件

3)字段过滤

4)数据条数:limit

5)字段是否存在

 


void query_test()
{
	mongocxx::instance instance{};
	mongocxx::uri uri("mongodb://127.0.0.1:27017");
	mongocxx::client client(uri);

	// 数据库
	mongocxx::database db = client["test"];
	// 集合
	mongocxx::collection col_comment = db["comment"];
	mongocxx::collection col_like = db["like"];

	// 查找
	try
	{
// 		auto filter = bsoncxx::builder::stream::document{} << "i" << bsoncxx::builder::stream::open_document <<
// 			"$gt" << 50 << "$lte" << 100 << bsoncxx::builder::stream::close_document << bsoncxx::builder::stream::finalize;
		// 查询条件
		auto filter = bsoncxx::builder::stream::document{} << "session" << 44 << bsoncxx::builder::stream::finalize;
		// 排序条件
		auto order = bsoncxx::builder::stream::document{} << "like" << -1 << bsoncxx::builder::stream::finalize;
		// 字段过滤
		//auto field = bsoncxx::builder::stream::document{} << "_id" << 1 << "session" << 1 << "iggid" << 1 << "content" << 1 << "like" << 1 << bsoncxx::builder::stream::finalize;
		auto field = bsoncxx::builder::stream::document{} << bsoncxx::builder::stream::finalize;
		mongocxx::options::find opts = mongocxx::options::find{};
		// 数据条数:limit(10)
		opts.sort(order.view()).projection(field.view()).limit(10);

		mongocxx::cursor cursor = col_comment.find(filter.view(), opts);
		if (cursor.begin() != cursor.end())
		{
			for (auto & doc : cursor)
			{
				// bson转json
				//std::cout << bsoncxx::to_json(doc) << "\n";
				std::cout << "find : _id[" << doc["_id"].get_oid().value.to_string() << "] session[" << doc["session"].get_int32() << "]\n";
				// 判断是否有此字段:parentid
				auto it = doc.find("parentid");
				if (it != doc.end())
				{
					std::cout << "find : _id[" << doc["parentid"].get_utf8().value.to_string() << "]\n";
				}
			}
		}
	}
	catch (const std::exception& e)
	{
		std::cout << "find error : " << e.what();
	}

}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值