Reputation:
I am trying to implement the following mongodb query in C
db.test.find({"timestamp": {"$exists":true}});
I thought it would be something like
bson query, existspart;
mongo_cursor cursor;
int i;
bson_init(&existspart);
bson_append_string ( &existspart, "$exists", "false" );
bson_finish(&existspart);
bson_init(&query);
bson_append_bson ( &query, "timestamp", &existspart );
bson_finish(&query);
mongo_cursor_init(&cursor, conn, "mydb.test");
mongo_cursor_set_query(&cursor, &query );
while( mongo_cursor_next( &cursor ) == MONGO_OK )
{
// blabla
}
But it does not work. What I am doing wrong?
Upvotes: 0
Views: 291
Reputation: 21
I used a slightly different syntax:
bson_t* existspart = BCON_NEW("$exists", BCON_BOOL(true));
bson_t *query = bson_new();
BSON_APPEND_DOCUMENT(query, "timestamp", existspart);
mongoc_cursor_t* cursor = MongoInterface::Instance().Find("db_name", query);
const bson_t *doc;
while (mongoc_cursor_next (cursor, &doc))
{
// Do stuff...
}
bson_destroy (existspart);
bson_destroy (query);
Upvotes: 0
Reputation: 156
replace
bson_append_string ( &existspart, "$exists", "false" );
with
bson_append_bool ( &existspart, "$exists", 1 );
or
bson_append_bool ( &existspart, "$exists", 0 );
if you do not want that field exist
Upvotes: 1