3

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);
Armfoot
  • 4,663
  • 5
  • 45
  • 60
Can Bayar
  • 497
  • 4
  • 16
  • _" it does not work as we expected"_ could you elaborate this a little? What is "not working" ? Compilation error ? Runtime error ? Wrong result ? – Sylvain Leroux Jul 03 '15 at 15:38
  • That's the weird part, it does not throw exception or give any error. It just does not sort the data, it gives the same result that an empty query gives. – Can Bayar Jul 04 '15 at 18:14

1 Answers1

3

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
                             "}");
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125