DZ Mongodb Essentials 2024

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

171 BROUGHT TO YOU IN PARTNERSHIP WITH

CONTENTS

•  Configuration Options
•  Using the Shell

MongoDB Essentials •  Diagnosing What's Happening


•  Index Options
•  Query, Update, and Aggregation
Flexible NoSQL for Humongous Data Pipeline Operators
•  Making Backups
•  Replica Set Maintenance
•  User Management
•  MongoDB Restrictions
UPDATED BY ABHISHEK GUPTA
PRINCIPAL DEVELOPER ADVOCATE, AWS •  Additional Resources
ORIGINAL BY VLAD MIHALCEA

MongoDB is a popular document-oriented NoSQL database that Table 2


offers flexible schema design. It stores data in JSON-like documents, OPTION DESCRIPTION
provides a rich query language, and supports client drivers in multiple
--config <filename> File for runtime configuration options
programming languages.
--dbpath <path> The directory where the mongod instance
stores its data
This Refcard covers MongoDB v4.4 onward up to v6.0. It is intended to
help you get the most out of MongoDB and assumes that you already --logpath <path> The path where MongoDB creates a file to send
diagnostic logging information
know the basics.
--logappend Appends new entries to the end of the existing
If you're just starting out, first, explore these resources: log file when the mongod instance restarts

--fork Enables daemon mode that runs the mongod


•  For installation notes, see https://www.mongodb.com/docs/
process in the background
manual/installation
--auth Enables authorization to control user access to
•  For a quick tutorial on basic operations, see https://www. database resources and operations
mongodb.com/docs/manual/tutorial/getting-started --keyFile <path> Path to a shared secret that enables
authentication on replica sets and sharding
•  For a list of supported languages, see https://www.mongodb.
--bind_ip <options> Specifies where mongod should listen for client
com/languages
connections; this could be hostnames, IP
addresses, and/or full Unix domain socket paths
CONFIGURATION OPTIONS
In this section, we cover configuration options for MongoDB.

SETUP OPTIONS
Startup options for MongoDB can be set on the command line or in a
configuration file. The syntax is slightly different between the two:

Table 1

COMMAND LINE CONFIG FILE

--dbpath <path> dbpath=<path>

--auth auth=true

Run mongod --help for a full list of options.

Table 2 in the next column lists some of the most useful.

© DZONE | REFCARD | MARCH 2024 1


From Planning to Performance:
MongoDB Upgrade
Best Practices

Whether you’re a seasoned DBA


well-versed in MongoDB or a
newcomer looking to harness its
potential, this ebook provides the
insights, strategies, and best
practices to guide you through
MongoDB upgrades, ensuring
they go as smoothly as possible
and your databases remain
optimized and secure.

Read the eBook


REFCARD | MONGODB ESSENTIALS

VIEW OPTIONS SEEING FUNCTION DEFINITIONS


If you started mongod with a bunch of options six months ago, how can If you don't understand what a function is doing, you can run it without
you see which options you used? The shell has a helper: the parentheses in the shell to see its source code:

> db.serverCmdLineOpts() > // run the function


{ "argv" : [ "./mongod", "--port", "30000" ], > db.serverCmdLineOpts()
"parsed" : { }, "ok" : 1 } { "argv" : [ "./mongod" ], "parsed" : { }, "ok" : 1
}
The parsed field is a list of arguments read from a config file. > // see its source
> db.serverCmdLineOpts
USING THE SHELL
This section covers topics around MongoDB shell usage. Note that This can be helpful for seeing what arguments the function expects or

the mongo shell was deprecated in MongoDB v5.0 and removed from what errors it can throw, as well as how to run it from another language.

MongoDB v6.0. The replacement shell is mongosh. USING EDIT


SHELL HELP The shell has limited multi-line support, so it can be difficult to program

There are a number of functions that give you a little help if you forget in. The shell helper edit makes this easier, which opens up a text

a command: editor, allowing you to edit variables from there. For example:

> // basic help > x = function() { /* some function we're going to


> help fill in */ }
Shell Help: > edit x
<opens emacs with the contents of x>
use
Set current database
show
Modify the variable in your editor, then save and exit. The variable will
'show databases'/'show dbs': Print a list of all be set in the shell.
available databases.
Either the EDITOR environment variable or a MongoDB shell variable
'show collections'/'show tables': Print a list
EDITOR must be set to use edit. You can set it in the MongoDB shell
of all collections for current database.
as follows:
'show profile': Prints system.profile
information. > EDITOR="/user/bin/emacs"

'show users': Print a list of all users for


Note that edit is not available from JavaScript scripts, only in the
current database.
interactive shell.
'show roles': Print a list of all roles for
current database. USING .mongoshrc.js
If a .mongoshrc.js file exists in your home directory, it will run on shell
'show log <type>': log for current connection,
if type is not set uses 'global' startup automatically. Use it to initialize any helper functions you use
regularly and remove functions you don't want to accidentally use. Use
'show logs': Print all logs.
the --norc option to prevent .mongoshrc.js from being loaded. For
exit example, if you would prefer to not have dropDatabase() available by
Quit the MongoDB shell with exit/exit()/.exit
default, you could add the following lines to your .mongoshrc.js file:
quit
Quit the MongoDB shell with quit/quit()
DB.prototype.dropDatabase = function() {
print("No dropping DBs!");
...
}
db.dropDatabase = DB.prototype.dropDatabase;
Note that there are separate help functions for databases, collections,
replica sets, sharding, administration, and more. Although not listed The example above will change the dropDatabase() helper to only
explicitly, there is also help for cursors: print a message, not to drop databases. Note: This technique should not
be used for security because a determined user can still drop a database
> // list common cursor functions
without the helper. However, removing dangerous admin commands,
> db.foo.find().help()
as shown in the example above, can help prevent fat-fingering. Here
are a couple suggestions for helpers you may want to remove from
You can use these functions and helpers as built-in cheat sheets. You
.mongoshrc.js:
can find the full list here: https://www.mongodb.com/docs/mongodb-
shell/reference/access-mdb-shell-help •  DB.prototype.shutdownServer

•  DBCollection.prototype.drop

© DZONE | REFCARD | MARCH 2024 3 BROUGHT TO YOU IN PARTNERSHIP WITH


REFCARD | MONGODB ESSENTIALS

•  DBCollection.prototype.ensureIndex INDEX USAGE


•  DBCollection.prototype.reIndex Use explain() to see which index MongoDB is using for a query.
verbosity specifies the mode, which determines the amount of
•  DBCollection.prototype.dropIndexes
returned information. Possible modes include allPlansExecution
PROMPT CHANGES (default), queryPlanner, and executionStats.
The shell prompt can be customized by setting the prompt variable to a
> db.runCommand({
function that returns a string: explain: {
count: "users",
prompt = function() { query: { age: { $gt: 30 } },
try { },
db.getLastError(); verbosity: "queryPlanner",
} });
catch (e) {
print(e); {
} explainVersion: '1',
return (new Date())+"$"; queryPlanner: {
} namespace: 'test.users',
indexFilterSet: false,
maxIndexedOrSolutionsReached: false,
If you set a prompt, it will be executed each time the prompt is drawn
maxIndexedAndSolutionsReached: false,
(thus, the example above would give you the time the last operation maxScansToExplodeReached: false,
completed). Try to include the db.getLastError() function call in winningPlan: { stage: 'COUNT', inputStage: {
stage: 'EOF' } },
your prompt. This is included in the default prompt and takes care of
rejectedPlans: []
server reconnection and returning errors from writes. },
command: { count: 'users', query: { age: { '$gt':
Also, always put any code that could throw an exception in a try/catch
30 } }, '$db': 'test' },
block, as shown in the example above. It's annoying to have your serverInfo: {
prompt turn into an exception! host: 'bdc9e348c602',
port: 27017,
DIAGNOSING WHAT'S HAPPENING version: '7.0.4',
gitVersion:
This section covers how to get detailed information on operations,
'38f3e37057a43d2e9f41a39142681a76062d582e'
index usage, replication status, and more. },
serverParameters: {
VIEWING AND KILLING OPERATIONS internalQueryFacetBufferSizeBytes: 104857600,
You can see current operations with the currentOp function: internalQueryFacetMaxOutputDocSizeBytes:
104857600,
> db.currentOp()
{ internalLookupStageIntermediateDocumentMaxSizeBytes:
"inprog" : [ 104857600,
{ internalDocumentSourceGroupMaxMemoryBytes:
"opid" : 123, 104857600,
"active" : false, internalQueryMaxBlockingSortMemoryUsageBytes:
"locktype" : "write", 104857600,
"waitingForLock" : false, internalQueryProhibitBlockingMergeOnMongoS: 0,
"secs_running" : 200, internalQueryMaxAddToSetBytes: 104857600,
"op" : "query",
"ns" : "foo.bar", internalDocumentSourceSetWindowFieldsMaxMemoryBytes:
"query" : { 104857600,
} internalQueryFrameworkControl: 'trySbeEngine'
... },
}, ok: 1
... }
]
}
There are several important fields in the output of explain():

Using the opid field from above, you can kill operations: •  explainVersion is the output format version.
•  command is the command being explained.
> db.killOp(123)
•  queryPlanner provides information about the
selected and rejected plans by the query optimizer.
Not all operations can be killed or will be killed immediately. In
general, operations that are waiting for a lock cannot be killed until •  executionStats provides execution details of the
they acquire the lock. accepted and rejected plans.

© DZONE | REFCARD | MARCH 2024 4 BROUGHT TO YOU IN PARTNERSHIP WITH


REFCARD | MONGODB ESSENTIALS

•  serverInfo provides information about the MongoDB instance. To see a member's view of the entire set, connect to it and run the
•  serverParameters provides details about the following command:
internal parameters. > rs.status()

TYPES OF CURSORS
This command returns a structured JSON output and shows you
Here are some common cursor types in MongoDB:
what it thinks the state and status of the other members are. Running
•  Standard cursor is the default type returned by rs.status() on a secondary node will show you which node the
db.collection.find(). It iterates over query results secondary is syncing from in the syncSourceHost field.
in batches, retrieving data on demand from the server.
SHARDING
•  Change Stream cursor is a real-time data monitor, notifying
To see your cluster's metadata (shards, databases, chunks, etc.),
you whenever a document in a collection is inserted,
execute the following command from the MongoDB shell (mongosh)
updated, deleted, or replaced.
connected to any member of the sharded cluster:
•  Tailable cursor is a cursor for a capped collection that remains
> db.printShardingStatus()
open after the client exhausts the results in the initial cursor.
•  Backup cursor is a type of tailable cursor that points to a If verbosity is set to true, it displays full details of the chunk distribution
list of backup files. Backup cursors are for internal use only.
across shards along with the number of chunks on each shard:
•  Orphaned cursor is a cursor that is not correctly
> db.printShardingStatus(true)
closed or iterated over in your app code. It can cause
performance issues.
sh.status can also be executed on a mongos instance to fetch sharding

HINTING configuration. Its output is the same as that of printShardingStatus:


Use hint() to force a particular index to be used for a query: > sh.status()

> db.foo.find().hint({x:1})
You can also connect to the mongos and see data about your shards,
databases, collections, or chunks by using use config, then querying
SYSTEM PROFILING
the relevant collections:
You can turn on system profiling to see operations currently happening
on a database. Note that there is a performance penalty to profiling, > use config
switched to db config
but it can help isolate slow queries.
> show collections
changelog
> db.setProfilingLevel(2) // profile all operations
chunks
> db.setProfilingLevel(1) // profile operations
collections
that take longer than 100ms
csrs.indexes
> db.setProfilingLevel(1, 500) // profile
databases
operations that take longer than 500ms migrationCoordinators
> db.setProfilingLevel(0) // turn off profiling mongos
> db.getProfilingLevel(1) // see current profiling rangeDeletions
setting settings
shards
Profile entries are stored in a capped collection called system.profile tags
version
within the database in which profiling was enabled. Profiling can be
turned on and off for each database.
Always connect to a mongos to get sharding information. Never connect
REPLICA SETS or write directly to a config server; always use sharding commands
To find replication lag information for each secondary node, connect to and helpers.
the primary node of the replica set and run this command:
After maintenance, sometimes mongos processes that were not
> rs.printSecondaryReplicationInfo() actually performing the maintenance will not have an updated
source: m1.demo.net:27002
version of the config. Either bouncing these servers or running the
syncedTo: Mon Feb 01 2023 10:20:40 GMT-0800
flushRouterConfig command is generally a quick fix to this issue:
(PST)
20 secs (0 hrs) behind the primary
> use admin
> db.runCommand({flushRouterConfig:1})
The above command prints a formatted output of the replica set
status. You can also use db.printReplicationInfo() to retrieve
Often this problem will manifest as setShardVersion failed errors.
the replica set member's oplog. Its output is identical to that of
rs.printReplicationInfo().

© DZONE | REFCARD | MARCH 2024 5 BROUGHT TO YOU IN PARTNERSHIP WITH


REFCARD | MONGODB ESSENTIALS

Don't worry about setShardVersion errors in the logs, but they The symbols in Table 4 indicate the following:
should not trickle up to your application. Note that you shouldn't get •  ✓ = matches
the errors from a driver unless the mongos it's connecting to cannot •  X = does not match
reach any config servers.
Table 4
INDEX OPTIONS OPERATOR EXAMPLE QUERY RESULT
The table below provides several index options. For a complete list,
$gt {numSold : ✓ {numSold: 1}
refer to: https://www.mongodb.com/docs/manual/reference/method/ $gte {$lt:3}}
X {numSold: "hello"}
$lt
db.collection.createIndex
$lte X {x : 1}
$ne
Table 3 $in {age : {$in : ✓ {age: 21}
$nin [10, 14, 21]}}
INDEX OPTION DESCRIPTION ✓ {age: [9, 10, 11]}
X {age: 9}
unique Creates a unique index on a collection to
prevent insertion or update of documents $all {hand : {$all : ✓ {hand: ["7", "8", "9",
["10","J","Q", "10", "J", "Q", "K", "A"]}
with duplicate index key values; it is false "K","A"]}}
by default. X {hand:["J","Q","K"]}
$not { $nor: [{ ✓ { "status": "active",
name If not specified, MongoDB generates the status: "active" "age": 70 }
index name by concatenating the names of }, { age: { $gte:
X { "status": "inactive",
indexed fields and the sort order. 65 } }] }
"age": 45 }
partialFilterExpression If specified, the index will only reference $mod {age : {$mod : ✓ {age: 50}
documents that match the provided filter [10, 0]}}
X {age: 42}
expression.
$exists {phone: {$exists: ✓ {phone: "555-555-5555"}
sparse If set to true, the index will only reference true}}
X {phones: ["555-555-5555",
documents with the specified field; it is "1-800-555-5555"]}
false by default.
$type* {age : {$type : ✓ {age : "42"}
expireAfterSeconds Time to live (in seconds) that controls 2}}
X {age : 42}
how long MongoDB retains documents in
$size {"top- ✓ {"top-three":["gold","sil
this collection. three":{$size:3}} ver","bronze"]}
hidden Controls whether the index is hidden from X {"top-three":["blue
the query planner. ribbon"]}
$regex {role: / ✓ {"top-three":["gold","sil
storageEngine Specifies storage engine during index admin.*/i} {role: ver","bronze"]}
creation. {$regex:'admin.*',
X {"top-three":["blue
$options: 'i' }}
ribbon"]}
$not { $nor: [{ status: ✓ { "status": "active",
QUERY OPERATORS "active" }, { age: "age": 70 }
Queries are generally of the form: { $gte: 65 } }] }
X { "status": "inactive",
"age": 45 }
{key : {$op : value}}
$all { genres: { $all: ✓ {
["fiction", "title": "The Da Vinci
"mystery"] } } Code",
For example:
"genres": ["fiction",
"mystery", "thriller"]
{age : {$gte : 18}} }
X {
There are three exceptions to this rule — $and, $or, and $nor — which "title": "Harry Potter
and the Sorcerer's Stone",
are all top level: "genres": ["fantasy",
"adventure"]
{$or : [{age: {$gte : 18}}, {age : {$lt : 18}, }

parentalConsent:true}}]} $size { players: { ✓ {


$size: 5 } } "team_name": "Red Team",
"players": ["John",
Updates are always of the form: "Emma", "Sarah", "Michael",
"David"]
{key : {$mod : value}} }
X {
For example: "team_name": "Blue Team",
"players": ["Alice", "Bob",
"Charlie"]
{age : {$inc : 1}} }

© DZONE | REFCARD | MARCH 2024 6 BROUGHT TO YOU IN PARTNERSHIP WITH


REFCARD | MONGODB ESSENTIALS

UPDATE OPERATORS
Table 5 includes commonly used MongoDB update operations:

Table 5

MODIFIER START DOC EXAMPLE MOD RESULT

$set {x:"foo"} {$set:{x:[1,2,3]}} {x:[1,2,3]}

$unset {x:"foo"} {$unset:{x:true}} {}

$inc {countdown:5} {$inc:{countdown:-1}} {countdown:4}

$push {votes:[-1,-1,1]} {$push:{votes:-1}} {votes:[-1,-1,1,-1}}


$pushAll

$pull {blacklist:["ip1","ip2","ip3"]} {$pull:{blacklist:"ip2"}} {blacklist:"ip1","ip3"}


$pullAll

$pop {queue:["1pm","3pm","8pm"]} {$pop:{queue:-1}} {queue:["3pm","8pm"]}

$addToSet {ints:[0,1,3,4]} {$addToSet:{ints:{$each:[1,2,3]}}} {ints:[0,1,2,3,4]}


$each

$rename {nmae:"sam"} {$rename:{nmae:"name"}} {name:"sam"}

$bit {permission:6} {$bit:{permissions:{or:1}}} {permission:7}

$min {"temp":25} { $min: { temp:20}} {"temp":20}

$setOnInsert {"name":"bob"} { $setOnInsert: { resetPassword: true } } { "name": "bob", "resetPassword": true }

$sort { "scores": [5, 8, 3, 9] } { $sort: { scores: 1 } } { "scores": [3, 5, 8, 9] }

AGGREGATION PIPELINE OPERATORS $project and $group can both take expressions, which can use the

The aggregation framework can be used to perform everything $fieldName syntax as shown below:

from simple queries to complex aggregations. To use it, pass the


Table 7
aggregate() function a pipeline of aggregation stages:
EXPRESSION OP EXAMPLE DESCRIPTION
> db.collection.aggregate({$match:{x:1}},
$add : ["$age", 1] Adds 1 to the age field.
... {$limit:10},
... {$group:{_id : "$age"}}) $divide : ["$sum", Divides the sum field by count.
"$count"]

Table 6 contains list of operators for the available stages: $mod : ["$sum", The remainder of dividing sum by count.
"$count"]
Table 6 $multiply : ["$mph", Multiplies mph by 24*365.
24, 365]
OPERATOR DESCRIPTION
$subtract : ["$price", Subtracts discount from price.
{$project : projection} Includes, excludes, renames, and "$discount"]
munges fields
$strcasecmp : ["ZZ", 1 if name is less than ZZ, 0 if name is ZZ,
{$match : match} Queries and takes an argument identical "$name"] -1 if name is greater than ZZ.
to that passed to find()
$substr : ["$phone", Gets the area code (first three
{$limit : num} Limits results to num 0, 3] characters) of phone.

{$skip : skip} Skips num results $toLower : "$str" Converts str to all lowercase.

{$sort : sort} Sorts results by the given fields $toUpper : "$str" Converts str to all uppercase.

{$group : group} Groups results using the expressions $ifNull : If mightExist is not null, it returns
["$mightExist", $add : mightExist. Otherwise, it returns the
given (see Table 7)
["$doesExist", 1]] result of the second expression.
{$unwind : field} Explodes an embedded array into its own
$cond : [exp1, exp2, If exp1 evaluates to true, it returns
top-level documents
exp3] exp2. Otherwise, it returns expr3.

To refer to a field, use the syntax $fieldName. For example, this


projection would return the existing time field with a new name, MAKING BACKUPS
"time since epoch": One of the ways to back up MongoDB data is to make a copy of the
database files while they are in a consistent state (i.e., not in the middle
{$project: {"time since epoch": "$time"}}
of being read from/to).

© DZONE | REFCARD | MARCH 2024 7 BROUGHT TO YOU IN PARTNERSHIP WITH


REFCARD | MONGODB ESSENTIALS

1. Use the fsyncLock() command, which flushes all in-flight writes to To prevent a secondary from being elected temporarily, connect to it
disk and prevents new ones: and issue the freeze command:

> db.fsyncLock() > rs.freeze(10*60) // # of seconds to not become


{ primary
info: 'now locked against writes, use
db.fsyncUnlock() to unlock', The freeze command is handy if you don't want to change priorities
lockCount: Long('1'),
permanently but need to do maintenance on the primary node.
seeAlso: 'http://dochub.mongodb.org/core/
fsynccommand',
DEMOTING A MEMBER
ok: 1
If a member is currently primary and you don't want it to be, use
}
stepDown:

2. Copy data files to a new location.


> rs.stepDown(10*60) // # of seconds to not try to
3. Use the fsyncUnlock() command to unlock the database: become primary again

> db.fsyncUnlock()
STARTING A MEMBER AS A STAND-ALONE SERVER
{ info: 'fsyncUnlock completed', lockCount:
For maintenance, often, it is desirable to start up a secondary and be
Long('0'), ok: 1
able to do writes on it (e.g., for building indexes). To accomplish this,
you can start up a secondary as a stand-alone mongod temporarily.
Note: To restore from this backup, copy the files to the correct server's
dbpath and start the mongod.
If the secondary was originally started with the following arguments:

Alternatively, if you have a filesystem that does filesystem $ mongod --dbpath /data/db --replSet setName --port
snapshots, your journal is on the same volume, and you haven't done 30000
anything stripy with RAID, you can take a snapshot without locking. In
this case, when you restore, the journal will replay operations to make Then shut it down cleanly and restart it with:
the data files consistent.
$ mongod --dbpath /data/db --port 30001

There are several other options for backing up your MongoDB data:
Note that the dbpath does not change but the port does, and the
•  Percona Backup for MongoDB (PBM) – An open-source and replSet option is removed (all other options can remain the same).
distributed solution for making consistent backups and This mongod will come up as a stand-alone server. The rest of the
restoring MongoDB sharded clusters and replica sets. You can replica set will be looking for a member on port 30000, not 30001, so
either use the command-line interface for backups on a running it will just appear to be "down" to the rest of the set.
server or manage backups from a web interface with PBM and
Percona Monitoring and Management. When you are finished with maintenance, restart the server with the
original arguments.
•  mongodump and mongorestore – mongodump is used to create a
binary export of MongoDB data, while mongorestore is used to USER MANAGEMENT
import this data back into a MongoDB instance. To check current user privileges:

•  Snapshots copies – filesystem snapshots capture a consistent > db.runCommand(


state of MongoDB data files at a point in time for fast and ... {
efficient backups. ... usersInfo:"manager",
... showPrivileges:true
REPLICA SET MAINTENANCE ... }
Replica sets allow a MongoDB deployment to remain available during ... )

the majority of a maintenance window.


To create a superAdmin:
KEEPING MEMBERS FROM BEING ELECTED
> use sensors
To permanently stop a member from being elected, change its
switched to db sensors
priority to 0:
> db.createUser(
... {
> var config = rs.config()
... user: "sensorsUserAdmin",
> config.members[2].priority = 0
... pwd: "password",
> rs.reconfig(config)

CODE CONTINUES IN ON NEXT PAGE

© DZONE | REFCARD | MARCH 2024 8 BROUGHT TO YOU IN PARTNERSHIP WITH


REFCARD | MONGODB ESSENTIALS

•  MongoDB non-indexed field sort will return results only if this


... roles:
... [ operation doesn't use more than 32 megabytes of memory.
... {
•  Aggregation pipeline stages are limited to 100 megabytes
... role: "userAdmin",
... db: "sensors" of RAM. When the limit is exceeded, an error is thrown. The
... } allowDiskUse option allows aggregation pipeline stages to use
... ]
... } temporary files for processing.
... )
•  A bulk operation is limited to 1,000 operations.

•  A database name is case-sensitive and may have up to 64


To view user roles:
characters. They cannot contain ., $, or \0 (the null character).
> use sensors Names can only contain characters that can be used on your
switched to db sensors
filesystem as filenames. Admin, config, and local are reserved
> db.getUser("sensorsUserAdmin")
{ database names. (Note that you can store your own data in
"_id" : "sensors.sensorsUserAdmin", them, but you should never drop them.)
"user" : "sensorsUserAdmin",
"db" : "sensors", •  Collections names cannot contain $ or null, start with the system.
"roles" : [ prefix, or be an empty string. Names prefixed with system. are
{ reserved by MongoDB and cannot be dropped — even if you
"role" : "userAdmin",
created the collection. Periods are often used for organization in
"db" : "sensors"
} collection names, but they have no semantic importance.
]
}
•  Field names cannot contain null.

To show role privileges:


ADDITIONAL RESOURCES
For next steps and more information, see the following resources:
> db.getRole( "userAdmin", { showPrivileges: true } )
•  Download MongoDB at http://www.mongodb.org/downloads

To grant a role: •  Documentation is available at http://docs.mongodb.org

•  See the roadmap and file bugs and request features at


> db.grantRolesToUser(
... "sensorsUserAdmin", http://jira.mongodb.org
... [
•  Ask questions in the MongoDB Developer Community forum at
... { role: "read", db: "admin" }
... ] https://www.mongodb.com/community/forums
... )

To revoke a role:

> db.revokeRolesFromUser(
UPDATED BY ABHISHEK GUPTA,
... "sensorsUserAdmin", PRINCIPAL DEVELOPER ADVOCATE, AWS
... [
Over the course of his career, Abhishek has worn
... { role: "userAdmin", db: "sensors" }
multiple hats including engineering, product
... ] management, and developer advocacy. Most of his
... ) work has revolved around open-source technologies,
including distributed data systems and cloud-native platforms.
Abhishek is also an open source contributor and avid blogger.
MONGODB RESTRICTIONS
Below are common limitations in MongoDB. For a full list, see
https://www.mongodb.com/docs/manual/reference/limits.
3343 Perimeter Hill Dr, Suite 100
•  The maximum document size is 16 megabytes. Nashville, TN 37211
888.678.0399 | 919.678.0300
•  The index entry total size must be less than 1,024 bytes.
At DZone, we foster a collaborative environment that empowers developers and
tech professionals to share knowledge, build skills, and solve problems through
•  A collection can have up to 64 indexes. content, code, and community. We thoughtfully — and with intention — challenge
the status quo and value diverse perspectives so that, as one, we can inspire
•  The index name (namespace included) cannot be longer than positive change through technology.
127 bytes (for version 4.0 or earlier).
Copyright © 2024 DZone. All rights reserved. No part of this publication may be
•  A replica set can have up to 50 members.
reproduced, stored in a retrieval system, or transmitted, in any form or by means
of electronic, mechanical, photocopying, or otherwise, without prior written
•  A shard key can have 512 bytes at most (for version 4.2 or earlier). permission of the publisher.
•  A shard key is always immutable (for version 4.2 or earlier).

© DZONE | REFCARD | MARCH 2024 9 BROUGHT TO YOU IN PARTNERSHIP WITH

You might also like