"MongoDB C driver 사용법 5-1 - FIND (SELECT)"에서
기본적인 select만 했다면
내가 원하는 필드만 찾고,
정렬도 하고,
최대 탐색수도 설정할수있도록
옵션을 지정해보겠습니다.
예제소스 고고
[출력 결과]
{ "uid" : "user5" }
bson_iter_type : 2
bson_iter_utf8 : user5
기본적인 select만 했다면
내가 원하는 필드만 찾고,
정렬도 하고,
최대 탐색수도 설정할수있도록
옵션을 지정해보겠습니다.
예제소스 고고
#include <bson.h>
#include <mongoc.h>
#include <stdio.h>
#define SERVER "mongodb://localhost:27017/"
#define DATABASE "MY_MONGO"
#define COLLECTION "MY_MONGO_COLLECTION"
int main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
mongoc_read_prefs_t *read_prefs;
bson_iter_t iter;
bson_iter_t value;
const bson_t *doc;
bson_t *filter;
bson_t *opts;
bson_error_t error;
char *str;
// mongoDB C driver 초기화 + DB 클라이언트 생성
mongoc_init ();
client = mongoc_client_new (SERVER);
mongoc_client_set_appname (client, "find_example");
// 컬랙션에 접근할 객체 생성
collection = mongoc_client_get_collection (client, DATABASE, COLLECTION);
// 탐색 조건
filter = bson_new ();
bson_append_int32 (filter, "birth_year", -1, 2001); // birth_year가 2001인것만 탐색
// 탐색 옵션 (최대 10개 탐색, uid를 역순으로 정렬)
opts = BCON_NEW (
"projection",
"{",
"uid", BCON_BOOL(true), // uid 필드 출력 허용 (_id를 제외한 나머지 필드는 알아서 배제된다)
"_id", BCON_BOOL(false), // _id 출력 배제 (직접 배제시키지 않는이상 무조건 출력됨)
"}",
"limit", BCON_INT64 (1),
"sort",
"{",
"uid", BCON_INT32 (-1),
"}");
// select 수행
cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);
// BSON 데이터 순서대로 탐색
// mongoc_cursor_next : 유효한 bson문서를 읽을경우 true 반환, 유효한 bson문서가 아니거나 커서가 소진되었을 경우 false 반환
while (mongoc_cursor_next (cursor, &doc)) {
// bson 객체를 문자열로 출력
str = bson_as_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
// bson 객체 내에서 특정 key에 해당하는 값 출력
bson_iter_init(&iter, doc);
bson_iter_find_descendant(&iter, "uid", &value);
printf("bson_iter_type : %d\n",bson_iter_type(&value)); // value 의 데이터타입 체크
printf("bson_iter_utf8 : %s\n",bson_iter_utf8(&value, NULL)); // 문자열 데이터 꺼내기
}
if (mongoc_cursor_error (cursor, &error)) {
fprintf (stderr, "An error occurred: %s\n", error.message);
}
bson_destroy (opts);
bson_destroy (filter);
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
[출력 결과]
{ "uid" : "user5" }
bson_iter_type : 2
bson_iter_utf8 : user5
댓글
댓글 쓰기