欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mongodb:带条件查询

程序员文章站 2022-05-23 09:17:58
...

主要演示了条件查收:

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();
	}

}