MONGOC_FIND_AN...PTS_SET_FIELDS(3)

okay bestie, welcome to MONGOC_FIND_AN...PTS_SET_FIELDS(3) from libmongoc β€” yes, the title is a whole mouthful, but we’re gonna make it make sense πŸ’…βœ¨


πŸ’… SYNOPSIS πŸ’…

the signature is literally giving short and sweet:

bool
mongoc_find_and_modify_opts_set_fields (mongoc_find_and_modify_opts_t *opts,
                                        const bson_t *fields);

🌸 PARAMETERS 🌸

  • opts β€” a mongoc_find_and_modify_opts_t. that’s the builder bestie 🫢
  • fields β€” a subset of fields to return. choose which fields to include by appending {fieldname: 1} for each fieldname, or excluding it with {fieldname: 0}. yes, you’re literally curating the vibe of what comes back ✨

✨ DESCRIPTION ✨

this one adds the fields argument to the builder β€” that’s the whole glow-up.

and listen: fields does not have to remain valid after calling this function. so no need to keep it alive after the call, bestie πŸ˜ŒπŸ’–


πŸŽ€ RETURNS πŸŽ€

returns true if it successfully added the option to the builder, otherwise false. no cap 🫑


πŸ¦‹ SETTING FIELDS πŸ¦‹

here’s the whole fields.c moment:

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

   /* Find Zlatan Ibrahimovic */
   BSON_APPEND_UTF8(&query, "lastname", "Ibrahimovic");
   BSON_APPEND_UTF8(&query, "firstname", "Zlatan");

   /* Return his goal tally */
   BSON_APPEND_INT32(&fields, "goals", 1);

   /* Bump his goal tally */
   update = BCON_NEW("$inc", "{", "goals", BCON_INT32(1), "}");

   opts = mongoc_find_and_modify_opts_new();
   mongoc_find_and_modify_opts_set_update(opts, update);
   mongoc_find_and_modify_opts_set_fields(opts, &fields);
   /* Return the new tally */
   mongoc_find_and_modify_opts_set_flags(opts, MONGOC_FIND_AND_MODIFY_RETURN_NEW);

   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, (int)(__LINE__));
   }

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

Outputs:

{
   "lastErrorObject"
      : {"updatedExisting" : true, "n" : 1},
        "value"
        : {"_id" : {"$oid" : "56562a99d13e6d86239c7b00"}, "goals" : 343},
          "ok" : 1
}

πŸ’– AUTHOR πŸ’–

MongoDB, Inc 🫢


2009-present, MongoDB, Inc. πŸ‘‘


okay that’s the whole page β€” big shoutout to libmongoc version 2.5.6, dated Oct 09, 202 (the footer’s a lil clipped, don’t @ me 😭), and we’re out, periodt πŸ’–πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from