BSON_ITER_INIT(3)

πŸ’– BSON_ITER_INIT(3) πŸ’–

okay so this is a page from the libbson manual and honestly? it's a little cutie. it's giving "tiny function, huge main character energy" ✨ let's get into it bestie 🫢


✨ SYNOPSIS ✨

bool
bson_iter_init (bson_iter_t *iter, const bson_t *bson);

that's the whole signature bestie, no cap πŸ’…


πŸŽ€ PARAMETERS πŸŽ€

  • iter: a bson_iter_t. yes. that one. the iterator itself πŸ¦‹
  • bson: a bson_t. the document you're about to vibe-check πŸ”

πŸ’œ DESCRIPTION πŸ’œ

so bson_iter_init() shall initialize iter to iterate upon the BSON document bson. shall!! it's contractual, it's serious, it's slay πŸ‘‘

here's the important part β€” the way that upon initialization, iter is placed before the first element. like, it hasn't walked in yet. it's in the hallway. it's doing its little pre-game stretch 🧚

so you, the caller, must call bson_iter_next(), bson_iter_find(), or bson_iter_find_case() to actually advance to an element. don't just sit there expecting the data to come to you, bestie β€” you gotta move 😭


🌸 RETURNS 🌸

returns true if the iter was successfully initialized. simple. iconic. periodt πŸ’…


πŸ”₯ EXAMPLE πŸ”₯

okay so here's you printing a doc's _id, first the long way:

static void
print_doc_id (const bson_t *doc)
{
   bson_iter_t iter;
   bson_oid_t oid;
   char oidstr[25];

   if (bson_iter_init (&iter, doc) && bson_iter_find (&iter, "_id") &&
       BSON_ITER_HOLDS_OID (&iter)) {
      bson_iter_oid (&iter, &oid);
      bson_oid_to_string (&oid, oidstr);
      printf ("%s\n", oidstr);
   } else {
      printf ("Document is missing _id.\n");
   }
}

and then the glow-up version πŸ¦‹

/* alternatively */

static void
print_doc_id (const bson_t *doc)
{
   bson_iter_t iter;
   bson_oid_t oid;
   char oidstr[25];

   if (bson_iter_init_find (&iter, doc, "_id") && BSON_ITER_HOLDS_OID (&iter)) {
      bson_iter_oid (&iter, &oid);
      bson_oid_to_string (&oid, oidstr);
      printf ("%s\n", oidstr);
   } else {
      printf ("Document is missing _id.\n");
   }
}

same energy, fewer calls. we love a shortcut that doesn't skip the safety checks πŸ’–


πŸ‘‘ AUTHOR πŸ‘‘

MongoDB, Inc


2009-present, MongoDB, Inc.


ngl if your doc has no _id the example will just tell you so very politely. that's it. that's the whole function. go forth and iterate πŸŽ€

okay bye bestie, this page was from libbson 2.5.6, dated Oct 09, 2026 β€” see you in the next manpage, mwah πŸ’‹πŸ’œ

πŸ“¦ where this page comes from