user3801149
user3801149

Reputation: 21

MongoDB C Driver - Constructing a $lte query BSON?

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

Upvotes: 2

Views: 1116

Answers (2)

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

Upvotes: 0

user2562047
user2562047

Reputation: 211

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!

Upvotes: 1

Related Questions