2

As follows, the code doesn't work. I'm a newbie about MongoDB C Driver. Could anyone help me to correct my code? Thanks a lot.

I want to implement the command "{"_id":{$lt:11832668}}).sort({"_id":-1}".

            bson        laoquery[1];
            memset( laoquery, 0, sizeof( laoquery ) );


            bson_init( laoquery );
                    bson_append_start_object( laoquery, "&lte" );
                            bson_append_long( laoquery, "_id", 11832668 );
                    bson_append_finish_object( laoquery );

                    bson_append_start_object( laoquery, "$orderby" );
                        bson_append_int( laoquery, "_id", -1);
                    bson_append_finish_object( laoquery );

            bson_finish( laoquery );
Stennie
  • 63,885
  • 14
  • 149
  • 175

2 Answers2

1

First off, I would suggest that you use a recent release of the MongoDB C driver. This appears to be using the legacy driver.

Using the new driver, (among many new features and performance improvements), you can use BCON to construct the query.

bson_t *query;
mongoc_cursor_t *cursor;
const bson_t *doc;

query = BCON_NEW (
   "$query", "{", "_id", "{", "$lt", BCON_INT32 (11832688), "}", "}",
   "$orderby", "{", "_id", BCON_INT32 (-1), "}"
);

cursor = mongoc_collection_find (collection, 0, 0, 0, 0, query, NULL, NULL);

while (mongoc_cursor_next (cursor, &doc)) {
   /* do something with doc */
}

mongoc_cursor_destroy (cursor);
bson_destroy (query);

Hope that helps!

oz123
  • 27,559
  • 27
  • 125
  • 187
user2562047
  • 211
  • 1
  • 3
  • 1
    does anybody have a decent link to see what is c driver actually capable of ? I seem to only find basic examples which are not so usefull in "real" life. For example how to use dates, use batch update with the whole document not just certain fields...am I the only one that feels this driver is lacking some good documentation? – v0d1ch Oct 07 '15 at 19:05
0

With mongoc_collection_find_with_opts you can do:

 filter = BCON_NEW ("_id", "{", "$lt", BCON_INT32 (11832668), "}");
 opts = BCON_NEW ("sort", "{", "_id", BCON_INT32 (-1), "}");
 mongoc_cursor_t *cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);

source and example is here http://mongoc.org/libmongoc/current/mongoc_collection_find_with_opts.html