Getting started with the MongoDB Shell
The MongoDB Shell is a convenient way to interactively work with MongoDB.
You can start it issuing the command mongo
in a shell.
Now you can show the available databases…
> show dbs
and easily switch to another database if necessary.
In this example we switch to the database planets
:
> use planets
Tip: You can specify the database to use when launching the shell by adding the name of the database as first parameter.
Tip: If you are stuck in the shell a good starting point is the
help
command.
Run a command from the regular shell
Sometimes it’s convenient to run a command directly from the regular shell:
$ mongo planets --eval ‘db.planets.find({owner:"Spiff"}).pretty().shellPrint()’
The MongoDB _id
field
Every document inside a collection has a unique _id
field.
If you do not specify one during insert or upsert MongoDB will create one for you (if not otherwise specified those will be of type ObjectId
).
You can check the uniqueness .
db.spaceheads.getIndexes()
find
examples
On our staging server we have a lot of automatically generated spaceheads.
Those spaceheads all share a common name prefix Spiff_
.
To get an idea of manually created spaceheads we use:
db.spaceheads.find({ name: { $not: /^Spiff_.*/ } }, {name: true}).pretty()
Find spacehead with largest nr
and missing captainsLog
aka null
in a spacehead document:
db.spaceheads.find({ captainsLog: {$ne:null}, {name: true}}).sort({"nr": -1}).limit(1)
Find all spaceheads who have the two roles captain
and clan leader
(and only return the name field):
db.spaceheads.find({roles: ["captain", "clan leader"] }, {_id: 0, name: 1})
Warning: In this type of queries the order of the items in the array matters!
The following query will find all spaceheads that have the role captain inside the array roles no matter where and what other roles are contained besides.
db.spaceheads.find({roles: "captain" })
Note: To match agains an array with exactly one entry
captain
you would use["captain"]
instead.
To query agains items at a specific position inside the array use the dot notation (find documents where role captain
is the first item):
db.spaceheads.find({roles.0: "captain" })
Find spacehead with largest nr
and empty captainsLog
aka []
in a spacehead document:
TODO: invest how to use Array query operator $size
db.spaceheads.find({ captainsLog: {$gt: []}, {name: true}}).sort({"nr": -1}).limit(1)
Please check out Query Operators in the docs for more details. Especially the section about Element Query Operators which cover some corner cases you might not have encountered so far…
Tip: You can add
.pretty()
at the end of a find command to generate beautified output.
update
examples
There are three different ways to update documents in MongoDB:
* updateOne
the first document matching the filter.
* updateMany
* replaceOne
Update a field of a know document with $set:
db.spaceheads.updateOne({ _id: ObjectId('4711') }, {$set: {active: false}})
Remove a field of a know document with $unset:
db.spaceheads.updateOne({ _id: ObjectId('4711') }, {$unset: {oldField: false}})
Rename substring in all documents of a collection. (e.g. 'Cpt. Spiff' -> 'Captain Spiff')
We look for the string Cpt.
followed by a space (\s
):
db.spaceheads.find({'name': {$regex: ‘^Cpt\.\s.*’}}).snapshot().forEach(function(doc) {
var updated_name = doc.name.replace('Cpt.', 'Captain');
db.apps.update(
{"_id": doc._id},
{ "$set": { "name": updated_name } }
);
});
Increase a numeric field (e.g. increase stuff of all space stations) with $inc
db.spaceStations.update({}, {$inc: {'cargoBay.stuff': 1001}}, {'multi':true})
In the following example we use $push
in combination with $slice
to keep a maximum of 10 log entries in a spacehead document:
db.spaceheads.updateOne({name: "Spiff"}, { $push: { captainsLog: { $each: [
{ eventType: "MONSTER_ENCOUNTER" }
], $slice: 10 }
}})
insert with type integer
db.planets.”save({intCounter”:NumberInt(0)});
Documentation link: Data Types in the mongo Shell