Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 961
Can Bayar Avatar asked Aug 08 '26 21:08

Can Bayar


1 Answers

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
                             "}");
like image 161
Sylvain Leroux Avatar answered Aug 13 '26 21:08

Sylvain Leroux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!