MONGOC_URI_T(3)

πŸ’… MONGOC_URI_T(3) β€” the libmongoc vibe check

okay bestie, grab your iced coffee because we're about to get into mongoc_uri_t, straight out of libmongoc. this is the struct that makes MongoDB connection strings make sense, and honestly? she's iconic.


✨ SYNOPSIS ✨

typedef struct _mongoc_uri_t mongoc_uri_t;

that's it. that's the whole synopsis. a little opaque little mystery. slay.


πŸ¦‹ DESCRIPTION πŸ¦‹

so mongoc_uri_t is basically a glow-up wrapper sitting on top of the MongoDB connection URI format. it gives you standardized parsing, plus a bunch of convenience methods so you can pull out the good stuff β€” things like replica hosts or your authorization info β€” without doing string gymnastics yourself. we love a struct that does the emotional labor for you.

if you want the full lore, go check the Connection String URI Reference on the MongoDB website. iykyk.


πŸŽ€ FORMAT πŸŽ€

here's the shape of it, and yes, the little numbers matter:

mongodb[+srv]://                             <1>
   [username:password@]                      <2>
   host1                                     <3>
   [:port1]                                  <4>
   [,host2[:port2],...[,hostN[:portN]]]      <5>
   [/[database]                              <6>
   [?options]]                               <7>
  1. "mongodb" is the specifier of the MongoDB protocol. use "mongodb+srv" with a single service name in place of "host1" to specify the initial list of servers with an SRV record.
  2. an optional username and password.
  3. the only required part of the uri. this specifies either a hostname, IPv4 address, IPv6 address enclosed in "[" and "]", or UNIX domain socket.
  4. an optional port number. defaults to :27017.
  5. extra optional hosts and ports. you'd specify multiple hosts, for example, for connections to replica sets.
  6. the name of the database to authenticate if the connection string includes authentication credentials. if /database is not specified and the connection string includes credentials, defaults to the 'admin' database.
  7. connection specific options.
πŸ’€ NOTE: option names are case-insensitive. do not repeat the same option (e.g. "mongodb://localhost/db?opt=value1&OPT=value2") since this may have unexpected results. fr fr, don't do it, it's giving chaos.

the MongoDB C Driver exposes constants for each supported connection option. these constants make it easier to discover connection options, but their string values can be used as well. so like, you've got options (literally).

for example, the following calls are equal. no cap:

uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_APPNAME "=applicationName");
uri = mongoc_uri_new ("mongodb://localhost/?appname=applicationName");
uri = mongoc_uri_new ("mongodb://localhost/?appName=applicationName");

see how appname, appName, and the constant all land in the same place? that's the case-insensitivity doing its thing. obsessed. 🫢


πŸ‘‘ REPLICA SET EXAMPLE πŸ‘‘

ok so imagine you wanna describe a connection to a replica set named 'test' with these mongod hosts:

  • db1.example.com on port 27017
  • db2.example.com on port 2500

you'd use a connection string that resembles the following:

mongodb://db1.example.com,db2.example.com:2500/?replicaSet=test

look at that. chef's kiss. πŸ”₯


🧚 SRV EXAMPLE 🧚

if you have configured an SRV record with a name like "_mongodb._tcp.server.example.com" whose records are a list of one or more MongoDB server hostnames, use a connection string like this:

uri = mongoc_uri_new ("mongodb+srv://server.example.com/?replicaSet=rs&appName=applicationName");

k so what actually happens under the hood: the driver prefixes the service name with "_mongodb._tcp.", then performs a DNS SRV query to resolve the service name to one or more hostnames. if this query succeeds, the driver performs a DNS TXT query on the service name (without the "_mongodb._tcp" prefix) for additional URI options configured as TXT records. multi-step, but she gets there. ⭐

on Unix, the MongoDB C Driver relies on libresolv to look up SRV and TXT records. if libresolv is unavailable, then using a "mongodb+srv" URI will cause an error. and if your libresolv lacks res_nsearch then the driver will fall back to res_search, which is not thread-safe. noted. πŸ™ˆ

set the environment variable MONGOC_EXPERIMENTAL_SRV_PREFER_TCP to prefer TCP for the initial queries. the environment variable is ignored for res_search. large DNS responses over UDP may be truncated due to UDP size limitations. DNS resolvers are expected to retry over TCP if the UDP response indicates truncation. some observed DNS environments do not set the truncation flag (TC), preventing the TCP retry. this environment variable is currently experimental and subject to change β€” so like, don't build your whole personality on it. πŸ’€


🌈 IPV4 AND IPV6 🌈

if connecting to a hostname that has both IPv4 and IPv6 DNS records, the behavior follows RFC-6555. a connection to the IPv6 address is attempted first. if IPv6 fails, then a connection is attempted to the IPv4 address. if the connection attempt to IPv6 does not complete within 250ms, then IPv4 is tried in parallel. whichever succeeds connection first cancels the other. the successful DNS result is cached for 10 minutes. genuinely very organized of her.

as a consequence, attempts to connect to a mongod only listening on IPv4 may be delayed if there are both A (IPv4) and AAAA (IPv6) DNS records associated with the host. 😭

to avoid a delay, configure hostnames to match the MongoDB configuration. that is, only create an A record if the mongod is only listening on IPv4. match the energy, basically.


πŸ“ CONNECTION OPTIONS πŸ“

here's the first batch of constants, their keys, their defaults, and what they actually do:

  • MONGOC_URI_RETRYREADS β€” key: retryreads, default: true. if "true" and the server is a MongoDB 3.6+ standalone, replica set, or sharded cluster, the driver safely retries a read that failed due to a network error or replica set failover.
  • MONGOC_URI_RETRYWRITES β€” key: retrywrites, default: true if driver built w/ TLS. if "true" and the server is a MongoDB 3.6+ replica set or sharded cluster, the driver safely retries a write that failed due to a network error or replica set failover. only inserts, updates of single documents, or deletes of single documents are retried.
  • MONGOC_URI_MAXADAPTIVERETRIES β€” key: maxadaptiveretries, default: 2. the maximum number of times the driver retries an operation that fails with a SystemOverloadedError. must be a non-negative integer. this option works with MongoDB Atlas Server Version 9.0 and above.

and that's just the first three β€” there is a whole lineup more where those came from, so stay tuned bestie πŸ’œ

  • MONGOC_URI_ENABLEOVERLOADRETARGETING, enableoverloadretargeting β€” default: false. Set it to "true" and the driver will deprioritize servers that handed back a SystemOverloadedError when it's picking a server to retry an operation on πŸ”₯. This one only works with MongoDB Atlas Server Version 9.0 and above, bestie β€” don't come for me if you're on an older one πŸ’…
  • MONGOC_URI_APPNAME, appname β€” default: Empty (no appname). This is your client application's name πŸŽ€ MongoDB literally uses this value when it logs connection information and profile information, like slow queries. So name your app, it's giving "main character energy" in the logs ✨
  • MONGOC_URI_TLS, tls β€” default: Empty (not set, same as false). Takes {true|false} and says whether TLS must be used or not πŸ” (See also mongoc_client_set_ssl_opts() and mongoc_client_pool_set_ssl_opts(), iykyk)
  • MONGOC_URI_COMPRESSORS, compressors β€” default: Empty (no compressors). A comma separated list of compressors, if any, to use to compress the wire protocol messages πŸ—œοΈ Snappy, zlib, and zstd are optional build time dependencies, and they enable the "snappy", "zlib", and "zstd" values respectively. So like, only the ones you built with are gonna slay πŸ’œ
  • MONGOC_URI_CONNECTTIMEOUTMS, connecttimeoutms β€” default: 10,000 ms (10 seconds). This setting applies to new server connections ⏱️ It's also used as the socket timeout for server discovery and monitoring operations, so it's lowkey doing double duty πŸ™ˆ
  • MONGOC_URI_SOCKETTIMEOUTMS, sockettimeoutms β€” default: 300,000 ms (5 minutes). The time in milliseconds to attempt to send or receive on a socket before the attempt times out ⏳ five whole minutes, she's patient fr fr
  • MONGOC_URI_REPLICASET, replicaset β€” default: Empty (no replicaset). The name of the Replica Set that the driver should connect to πŸ‘‘ gotta know which squad you're rolling with
  • MONGOC_URI_ZLIBCOMPRESSIONLEVEL, zlibcompressionlevel β€” default: -1. When the MONGOC_URI_COMPRESSORS includes "zlib", this option configures the zlib compression level, when the zlib compressor is used to compress client data 🧚 dial in that compression, no cap
  • MONGOC_URI_LOADBALANCED, loadbalanced β€” default: false. If true, this indicates the driver is connecting to a MongoDB cluster behind a load balancer βš–οΈ like, there's a whole balancer in front, respectfully
  • MONGOC_URI_SRVMAXHOSTS, srvmaxhosts β€” default: 0. If zero, the number of hosts in DNS results is unlimited 🌈 If greater than zero, the number of hosts in DNS results is limited to being less than or equal to the given value β€” so basically a cap on how many hosts you're willing to catch 🫢
⚠️ WARNING, bestie, read this one fr fr ⚠️ Setting any of the *timeoutMS options above to either 0 or a negative value is discouraged β€” it's giving unspecified and inconsistent behavior, and nobody has time for that πŸ’€ The "default value" that historically got specified as a fallback for 0 or a negative value is NOT related to the default values for the *timeoutMS options documented above. Not the same thing, not cousins, not even mutuals πŸ™ˆ The meaning of a timeout of 0 or a negative value may vary depending on the operation being executed β€” even when it's specified by the same URI option. Yeah. Chaotic behavior. We don't love it. To specify the documented default value for a *timeoutMS option, use the MONGOC_DEFAULT_* constants defined in mongoc-client.h instead. That's the ✨ correct ✨ way.

✨ AUTHENTICATION OPTIONS ✨

Okay so this is the whole "prove who you are" era of the URI, and honestly it ate πŸ‘‘

  • MONGOC_URI_AUTHMECHANISM β€” key: authmechanism β€” specifies the mechanism to use when authenticating as the provided user. Want to know which values actually work? See Authentication for supported values, iykyk πŸ¦‹.
  • MONGOC_URI_AUTHMECHANISMPROPERTIES β€” key: authmechanismproperties β€” additional properties for the specified mechanism, using key-value pair format, e.g. key1:value1,key2:value2. Little comma-separated cuties πŸ’….
  • MONGOC_URI_AUTHSOURCE β€” key: authsource β€” the name of the database to which authentication commands are sent, or $external depending on the specified mechanism. It overrides the auth database in the URI when applicable. Main character energy, honestly β€” it just takes over πŸ‘‘.
  • ENVIRONMENT β€” the name of a built-in OIDC provider integration. Must be one of ["azure", "gcp", "k8s"]. that's it, that's the list, don't try to be cute with it πŸ’…
  • TOKEN_RESOURCE β€” the URI of the target resource. heads up tho: ENVIRONMENT must be one of ["azure", "gcp"] for this one, ok? πŸ¦‹
⚠️ WARNING, bestie, read this twice: a TOKEN_RESOURCE property value MUST NOT contain the comma character "," when specified as a connection string query option, even when percent-encoded. Like, not even encoded. A value containing a comma character may be set using mongoc_uri_set_mechanism_properties() instead. However β€” and this is the slay part β€” the value MAY contain the colon character ":", as only the first colon is interpreted as a key-value delimiter. so colons ate, commas did not 😭

🌸 GSSAPI

  • SERVICE_NAME β€” Optional. Defaults to "mongodb". cute default, no notes ✨
  • CANONICALIZE_HOST_NAME β€” Optional. Must be one of ["false", "true"]. "false" performs no canonicalization (aka "none"). "true" performs a forward DNS lookup and then a reverse lookup on that value to canonicalize the hostname (aka "forwardAndReverse"). so like, one option, two whole aliases, iykyk πŸ”₯
  • SERVICE_REALM β€” Optional. May be needed for cross-realm authentication where the user and service exist in different realms. different realms = different vibes, apparently 🫢
  • SERVICE_HOST β€” Optional. May be needed to use a service host that differs from the initial role. literally just "what if the host isn't the first one" energy πŸ‘‘

πŸ’œ MONGODB-AWS

  • AWS_SESSION_TOKEN β€” Optional. An AWS session token to use for authentication with temporary credentials. temporary credentials, permanent icon behavior πŸŽ€

🧚 Deprecated Mechanism Property Options

these ones are, unfortunately, aging out β€” the following options have been deprecated and may be removed from future releases of libmongoc. so like… use them and enjoy them while they're here, but don't build your whole personality on them πŸ™ˆ

  • MONGOC_URI_CANONICALIZEHOSTNAME / key canonicalizehostname β€” deprecated for MONGOC_URI_AUTHMECHANISMPROPERTIES / key authmechanismproperties (specifically CANONICALIZE_HOST_NAME). the glow-up is real πŸ’…
  • MONGOC_URI_GSSAPISERVICENAME / key gssapiservicename β€” deprecated for MONGOC_URI_AUTHMECHANISMPROPERTIES / key authmechanismproperties (specifically SERVICE_NAME). same deal, new home, periodt ⭐

πŸ”’ TLS OPTIONS

okay this is the security section and honestly? iconic. each constant has a matching query key, here we go πŸ‘‘

  • MONGOC_URI_TLS β†’ key tls β€” {true|false}, indicating if TLS must be used. binary choice, no in-between, we love a clear boundary 🌈
  • MONGOC_URI_TLSCERTIFICATEKEYFILE β†’ key tlscertificatekeyfile β€” path to PEM formatted Private Key, with its Public Certificate concatenated at the end. yes, concatenated, like literally glued together at the tail, that's the whole assignment πŸŽ€
  • MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD β†’ key tlscertificatekeypassword β€” the password, if any, to use to unlock encrypted Private Key. only needed if the key is encrypted, otherwise you can just vibe πŸ¦‹
  • MONGOC_URI_TLSCAFILE, key tlscafile β€” one CA, or a whole bundle of Certificate Authorities, that we're gonna consider trusted πŸ’– like the guest list at the function. If you're on it, you're in.
  • MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, key tlsallowinvalidcertificates β€” accept and ignore certificate verification errors. All of 'em. Untrusted issuer? Expired? Whatever it is? Yeah bestie, we're simply not looking πŸ‘€ (it's giving "no thoughts, head empty").
  • MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, key tlsallowinvalidhostnames β€” skip the hostname verification of the certificate. So like, a totally valid cert that was issued for a different hostname? Accepted. That's literally the Man In The Middle scenario and we're just letting it in the door πŸ™ˆ
  • MONGOC_URI_TLSINSECURE, key tlsinsecure β€” {true|false}, telling you whether insecure TLS options should be used. Currently this implies both MONGOC_URI_TLSALLOWINVALIDCERTIFICATES and MONGOC_URI_TLSALLOWINVALIDHOSTNAMES. One switch, two very questionable decisions, periodt πŸ’…
  • MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK, key tlsdisablecertificaterevocationcheck β€” {true|false}, indicating if revocation checking (CRL / OCSP) should be disabled.
  • MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK, key tlsdisableocspendpointcheck β€” {true|false}, indicating if OCSP responder endpoints should not be requested when an OCSP response is not stapled.

✨ friendly lil heads up ✨ β€” see Configuring TLS for the deets on these options and on building libmongoc with TLS support. It's the assigned reading, bestie, no skipping 🫢

πŸ’€ DEPRECATED SSL OPTIONS πŸ’€

Okay so real talk: the following options have been deprecated and may legitimately be removed from future releases of libmongoc. They're not gone yet, but they are lowkey on their way out the door πŸšͺπŸ‘‹ So if you see them in your config, that's your sign to migrate. This is your main character moment to update.

Here's the glow-up map β€” old constant and key on the left, what replaced them on the right:

  • MONGOC_URI_SSL, key ssl β†’ deprecated for MONGOC_URI_TLS, key tls
  • MONGOC_URI_SSLCLIENTCERTIFICATEKEYFILE, key sslclientcertificatekeyfile β†’ deprecated for MONGOC_URI_TLSCERTIFICATEKEYFILE, key tlscertificatekeyfile
  • MONGOC_URI_SSLCLIENTCERTIFICATEKEYPASSWORD, key sslclientcertificatekeypassword β†’ deprecated for MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, key tlscertificatekeypassword
  • MONGOC_URI_SSLCERTIFICATEAUTHORITYFILE, key sslcertificateauthorityfile β†’ deprecated for MONGOC_URI_TLSCAFILE, key tlscafile
  • MONGOC_URI_SSLALLOWINVALIDCERTIFICATES, key sslallowinvalidcertificates β†’ deprecated for MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, key tlsallowinvalidcertificates
  • MONGOC_URI_SSLALLOWINVALIDHOSTNAMES, key sslallowinvalidhostnames β†’ deprecated for MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, key tlsallowinvalidhostnames

That's the whole deprecated lineup β€” every single one of them swapped the ssl prefix for a tls prefix and kept it moving πŸ’« (and yes, you clocked it correctly: sslclientcertificatekeypassword maps to tlscertificatekeypassword, not ...keyfilepassword β€” that's just how it is, iykyk πŸŽ€).

🌈 SERVER DISCOVERY, MONITORING, AND SELECTION OPTIONS 🌈

okay so bestie, this is the whole server-discovery situation, and it’s honestly kind of a lot, but we’re gonna get through it together πŸ’–

Clients in a mongoc_client_pool_t share a topology scanner that runs on a background thread. The thread wakes every heartbeatFrequencyMS (default 10 seconds) to scan all MongoDB servers in parallel. Whenever an application operation requires a server that is not known β€” for example, if there is no known primary and your application attempts an insert β€” the thread rescans all servers every half-second. In this situation the pooled client waits up to serverSelectionTimeoutMS (default 30 seconds) for the thread to find a server suitable for the operation, then returns an error with domain MONGOC_ERROR_SERVER_SELECTION.

Technically, the total time an operation may wait while a pooled client scans the topology is controlled both by serverSelectionTimeoutMS and connectTimeoutMS. The longest wait occurs if the last scan begins just at the end of the selection timeout, and a slow or down server requires the full connection timeout before the client gives up. 😭

A non-pooled client is single-threaded. Every heartbeatFrequencyMS, it blocks the next application operation while it does a parallel scan. This scan takes as long as needed to check the slowest server: roughly connectTimeoutMS. Therefore the default heartbeatFrequencyMS for single-threaded clients is greater than for pooled clients: 60 seconds.

By default, single-threaded (non-pooled) clients scan only once when an operation requires a server that is not known. If you attempt an insert and there is no known primary, the client checks all servers once trying to find it, then succeeds or returns an error with domain MONGOC_ERROR_SERVER_SELECTION. But if you set serverSelectionTryOnce to "false", the single-threaded client loops, checking all servers every half-second, until serverSelectionTimeoutMS.

The total time an operation may wait for a single-threaded client to scan the topology is determined by connectTimeoutMS in the try-once case, or serverSelectionTimeoutMS and connectTimeoutMS if serverSelectionTryOnce is set "false".


πŸŽ€ THE CONSTANTS, KEYS & DESCRIPTIONS πŸŽ€

  • MONGOC_URI_HEARTBEATFREQUENCYMS β€” key: heartbeatfrequencyms. The interval between server monitoring checks. Defaults to 10,000ms (10 seconds) in pooled (multi-threaded) mode, 60,000ms (60 seconds) in non-pooled mode (single-threaded). ⏰
  • MONGOC_URI_SERVERSELECTIONTIMEOUTMS β€” key: serverselectiontimeoutms. A timeout in milliseconds to block for server selection before throwing an exception. The default is 30,0000ms (30 seconds). πŸ’…
  • MONGOC_URI_SERVERSELECTIONTRYONCE, serverselectiontryonce β€” bestie, this one decides how hard the driver tries to find a server 🎯 set it to "true" and the driver scans the topology exactly once after server selection fails, then either picks a server or straight up returns an error (no more searching, it's done, periodt πŸ’…). Set it to false and the driver keeps searching for a suitable server for up to serverSelectionTimeoutMS milliseconds, pausing a half second between attempts πŸ• β€” very "i'll wait for you" energy. The default for serverSelectionTryOnce is "false" for pooled clients, otherwise "true". And heads up: pooled clients ignore serverSelectionTryOnce entirely β€” instead they signal the thread to rescan the topology every half-second until serverSelectionTimeoutMS expires. iykyk ✨
  • MONGOC_URI_SOCKETCHECKINTERVALMS, socketcheckintervalms β€” okay so this one only applies to single threaded clients 🧡 (single-threaded girlies rise). If a socket hasn't been used within this time, its connection gets checked with a quick "hello" call before it's used again πŸ‘‹ β€” like a little vibe check before you let it back in. Defaults to 5,000ms (5 seconds). no cap 🫢
  • MONGOC_URI_DIRECTCONNECTION, directconnection β€” if "true", the driver connects to a single server directly and will not monitor additional servers πŸ”’ main character energy, one server only. If "false", the driver connects based on the presence and value of the replicaSet option 🌈 β€” so it's out here reading the room before deciding.

πŸ’€ real talk though: setting any of the *TimeoutMS options above to 0 will be interpreted as "use the default value". so like… you think you turned it off, but you actually just said "surprise me" πŸ™ˆ defaults are iconic for a reason, bestie.

πŸ’… CONNECTION POOL OPTIONS

Okay bestie, these options are the ones that control how a mongoc_client_pool_t behaves β€” the whole pool vibe. Quick heads-up though: a non-pooled mongoc_client_t literally ignores all of these. Like, does not care. Not its business. πŸ™ˆ

So here's the roster:

  • MONGOC_URI_MAXPOOLSIZE / key maxpoolsize β€” the maximum number of clients a mongoc_client_pool_t will create in total, and yes that counts both the ones chilling in the pool and the ones currently checked out. Default is 100. And the moment you hit that cap? mongoc_client_pool_pop() just blocks until some other thread pushes a client back. So everyone waits in line like it's a sold-out concert 🎀
  • MONGOC_URI_WAITQUEUETIMEOUTMS / key waitqueuetimeoutms β€” the maximum time to wait for a client to actually become available from the pool. Basically the "how long am I willing to stand here before I give up" timer ⏳

✨ WRITE CONCERN OPTIONS ✨

Now for the write concern options β€” this is where you decide how much reassurance you need, and honestly it's giving trust issues in the best way 🫢

  • MONGOC_URI_W / key w β€” determines the write concern (aka the guarantee). Valid values are:
    • 0 β€” the driver will not acknowledge write operations, but it will pass or handle any network and socket errors that it receives over to the client. ⚠️ And heads up: if you disable write concern but enable the getLastError command's w option, that w overrides the w option. Ik, ik β€” it's a whole thing.
    • 1 β€” gives you basic acknowledgement of write operations. By specifying 1, you're requiring that a standalone mongod instance, or the primary for replica sets, acknowledge all write operations. πŸ’– And for drivers released after the default write concern change, this is the default write concern setting. So it's the main character of defaults πŸ‘‘
    • majority β€” for replica sets, if you pass this special majority value to the w option, write operations will only return successfully after a majority of the configured replica set members have acknowledged the write operation. It's giving "I need the group chat to all agree before I do anything" energy πŸ’€βœ¨
  • n = for replica sets, if you specify a number n greater than 1, operations with this write concern return only after n members of the set have acknowledged the write. ⚠️ and if you set n to a number that's greater than the number of available set members β€” or members that actually hold data β€” MongoDB will wait, potentially indefinitely, for these members to become available. like it will just sit there. forever. bestie do not do this to yourself 😭
    • tags = for replica sets, you can specify a tag set to require that all members of the set that have these tags configured return confirmation of the write operation. πŸ’…

  • MONGOC_URI_WTIMEOUTMS, key wtimeoutms β€” the time in milliseconds to wait for replication to succeed, as specified in the w option, before timing out. ⏱️ and here's the vibe check: when wtimeoutMS is 0, write operations will never time out. ever. no cap. 🫢
  • MONGOC_URI_JOURNAL, key journal β€” controls whether write operations will wait until the mongod acknowledges the write operations and commits the data to the on disk journal. πŸ““
    • true = enables journal commit acknowledgement write concern. equivalent to specifying the getLastError command with the j option enabled. slay ✨
    • false = does not require that mongod commit write operations to the journal before acknowledging the write operation. this is the default option for the journal parameter. 🌸

πŸ¦‹ READ CONCERN OPTIONS πŸ¦‹

  • MONGOC_URI_READCONCERNLEVEL, key readconcernlevel β€” the level of isolation for read operations. if the level is left unspecified, the server default will be used. see readConcern in the MongoDB Manual for details. iykyk πŸ“–

πŸ‘‘ READ PREFERENCE OPTIONS πŸ‘‘

when connected to a replica set, the driver chooses which member to query using the read preference, and the whole little selection ceremony goes like this:

  1. choose members whose type matches "readPreference". 🎯
  2. from these, if there are any tags sets configured, choose members matching the first tag set. if there are none, fall back to the next tag set and so on, until some members are chosen or the tag sets are exhausted. no luck? keep sliding down the list πŸ’«
  3. from the chosen servers, distribute queries randomly among the server with the fastest round-trip times. these include the server with the fastest time and any whose round-trip time is no more than "localThresholdMS" slower. ⚑

and now, the moment we've all been waiting for β€” the read preference constants table, with its three little columns: Constant, Key, Description. the rows are literally right there, so stay tuned bestie, we're not done yet πŸ’–

  • MONGOC_URI_READPREFERENCE, key readpreference β€” bestie this one sets the replica set read preference for this connection, and it overrides any secondaryOk value you set elsewhere, so like… it wins, periodt. The read preference values are:
    • primary (the default, obvs)
    • primaryPreferred
    • secondary
    • secondaryPreferred
    • nearest
  • MONGOC_URI_READPREFERENCETAGS, key readpreferencetags β€” a representation of a tag set πŸŽ€. See also Tag Sets, iykyk.
  • MONGOC_URI_LOCALTHRESHOLDMS, key localthresholdms β€” how far to distribute queries, beyond the server with the fastest round-trip time. By default, only servers within 15ms of the fastest round-trip time receive queries. It's giving "latency window," it's giving fairness πŸ’«.
  • MONGOC_URI_MAXSTALENESSSECONDS, key maxstalenessseconds β€” the maximum replication lag, in wall clock time, that a secondary can suffer and still be eligible. Heads up tho: the smallest allowed value for maxStalenessSeconds is 90 seconds. No going under, fr fr.
NOTE: πŸ’€ when you're connecting to more than one mongos, libmongoc's localThresholdMS applies only to the selection of mongos servers. The threshold for selecting among replica set members in shards is controlled by the mongos's localThreshold command line option. Two different thresholds, two different jobs β€” don't mix them up 🫢.

🌈 LEGACY OPTIONS 🌈

For historical reasons, the following options are available. They should however not be used πŸ™ˆ. Like, they exist, but please don't.

  • MONGOC_URI_SAFE, key safe β€” {true|false}, same as w={1|0}. That's it, that's the whole vibe. Retired but still hanging around the group chat 😭.

πŸ‘‘ AUTHOR πŸ‘‘

MongoDB, Inc

2009-present, MongoDB, Inc.


and that's a wrap on the whole page, bestie!! πŸŒΈπŸ¦‹ this was MONGOC_URI_T(3) version 2.5.6, dated Oct 09, 2026 β€” go build something iconic with it, mwah πŸ’…πŸ’–βœ¨

πŸ“¦ where this page comes from