Search code examples
mongodbsortingmongo-c-driver

Sorting by Subfields in Mongo C-Driver


We are trying to create a query in order to programmatically get an ordered cursor of a collection. There is a single example given in mongodb website and it is not even a working one.

What we are trying to do is to sort our collection by two fields that we named as timestamp.seconds and timestamp.nanoseconds. Our collection is indexed by these fields and we are able to sort the data using the code below in mongo shell:

db.Data.find().sort({"timestamp.seconds": 1, "timestamp.nanoseconds": 1})

How can we create the same query by using the C-driver? We tried the code given below and it does not work as we expected.

mongoc_cursor_t *cursor;
bson_t *query;

query = BCON_NEW("$query", "{", "}", "$orderby", "{",
                 "timestamp.seconds: 1, timestamp.nanoseconds: 1", "}");
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0,
                                 query, NULL, NULL);

Solution

  • You do not use the correct syntax when you build your query using BCON_NEW:

    query = BCON_NEW("$query", "{", "}",
                     "$orderby", "{",
                                      "timestamp.seconds",     BCON_INT32(1),
                                      "timestamp.nanoseconds", BCON_INT32(1),
                            //        ^^^^^^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^
                            //                key                  value
                                 "}");