mongoc_find_and_modify_opts_set_sort() — MongoDB C Driver 1.9.2

- MongoDB C Driver 1.9.2 »
- API Reference »
- mongoc_find_and_modify_opts_t

# mongoc_find_and_modify_opts_set_sort()

## Synopsis

    bool
    mongoc_find_and_modify_opts_set_sort (mongoc_find_and_modify_opts_t *opts,
                                          const bson_t *sort);

## Parameters

- `opts`: A mongoc_find_and_modify_opts_t.
- `sort`: Determines which document the operation modifies if the query selects multiple documents. findAndModify modifies the first document in the sort order specified by this argument.

## Description

Adds sort argument to the builder.

`sort` does not have to remain valid after calling this function.

## Returns

Returns `true` if it successfully added the option to the builder, otherwise `false`.

## Setting sort

sort.c

    void
    fam_sort (mongoc_collection_t *collection)
    {
       mongoc_find_and_modify_opts_t *opts;
       bson_t *update;
       bson_t sort = BSON_INITIALIZER;
       bson_t reply;
       bson_error_t error;
       bson_t query = BSON_INITIALIZER;
       bool success;

       /* Find all users with the lastname Ibrahimovic */
       BSON_APPEND_UTF8 (&query, "lastname", "Ibrahimovic");

       /* Sort by age (descending) */
       BSON_APPEND_INT32 (&sort, "age", -1);

       /* Bump his goal tally */
       update = BCON_NEW ("$set", "{", "oldest", BCON_BOOL (true), "}");

       opts = mongoc_find_and_modify_opts_new ();
       mongoc_find_and_modify_opts_set_update (opts, update);
       mongoc_find_and_modify_opts_set_sort (opts, &sort);

       success = mongoc_collection_find_and_modify_with_opts (
          collection, &query, opts, &reply, &error);

       if (success) {
          char *str;

          str = bson_as_canonical_extended_json (&reply, NULL);
          printf ("%s\n", str);
          bson_free (str);
       } else {
          fprintf (
             stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
       }

       bson_destroy (&reply);
       bson_destroy (update);
       bson_destroy (&sort);
       bson_destroy (&query);
       mongoc_find_and_modify_opts_destroy (opts);
    }

Outputs:

    {
       "lastErrorObject" : {"updatedExisting" : true, "n" : 1},
                           "value" : {
                              "_id" : {"$oid" : "56562a99d13e6d86239c7b00"},
                              "age" : 35,
                              "firstname" : "Zlatan",
                              "goals" : 343,
                              "lastname" : "Ibrahimovic",
                              "profession" : "Football player",
                              "position" : "striker",
                              "author" : true
                           },
                                     "ok" : 1
    }

Created using Sphinx 1.6.5, based on Sphinx Readable Theme.