[DATABASE - MONGO] Working with MongoDB Shell
I. Introduction
mongo
shell is an interactive JS interface to MongoDB.mongo
shell uses commands to perform direct operations to the database such as query, update, etc...
II. Commands to work with mongo shell
1. Basic commands
- Open
Command Prompt
> typemongo
command to open mongo shell. show dbs
: shows all database you have.use databaseName
: switches to the database if it exists, else create new database.db
: shows the current database you are using.show collections
: shows all collections in the current database.exit
: exits the shell.
2. Adding new documents to a collection
db.collectionName.insertOne({bson})
: inserts one document at a timedb.collectionName.insertMany([{bson}, {bson}])
: insert many documents at a time
// opens userRelatedInfo database
use userRelatedInfo
// adds user named Vivian to the users collectoin
db.users.insertOne(
{
name: "Vivian",
sex: "Female"
}
)
3. Finding documents
db.collectionName.findOne({})
: returns the first document in the collection.db.collectionName.findOne({field: "value", field1: "value"})
: returns the first document matching the condition.db.collectionName.find()/find({})
: lists the first 20 documents >it
for more documents.db.collectionName.find({field: "value", field1: "value"})
: returns all documents maching the condition.db.collectionName.find({condtion},{fieldName: 1, fieldName: 1})
: returns documents maching the condition, arg2 to specified which field can be printed to the shell.
{ "_id" : ObjectId("64e13bdf6847f9e80d312d29"), "name" : "Vivian", "sex" : "Female", "rank":10 }
// finds user with name Vivian and only display her rank
db.users.find({"name": "Vivian"}, {rank: 1, _id: 0})
4. Sorting and limiting data
db.collectionName.find(condition).count()
: returns the number of matching documents.db.collectionName.find(condition).limit(number)
: prints only a number of document based on number specified.db.collectionName.find(condition).sort({field: number})
: sorts the matching documents based on number specified, if number > 1, field is sorted in ascending order. if number < 1, it sorts in decending order.
5. Complex query with operators
$gt
,$lt
,$lte
,$gte
// finds all users whoes age is greater than 18
db.users.find( { "age": { $gt: 18 } } )
$or
// matches users whose age is 18 or 19
db.users.find( {$or: [{age: 18}, {age: 19}] })
$in
: matches in range$nin
: not matches in range
// matches users whose age is between 18-20
dbdb.users.find({ "age": {$in: [18,19,20]} })
// matches users whose age is less than 18 and greater than 20
dbdb.users.find({ "age": {$nin: [18,19,20]} })
$inc
: increases value$pull
: takes out a value of an array$push
: adds a new value to an array$each
: loops
6. Deleting documents
db.collectionName.deleteOne({field: value})
: deletes the first document matching the condition.db.collectionName.deleteMany({condition})
: deletes all documents matching the condition.
7. Updating documents
db.collectionName.updateOne({name: "Vivian"}, {$set: {name: "Vivian Vu", rank: 8}})
: finds the first document matching the condition then updates its value based on arg2.db.collectionName.updateMany({condition},{$set: {field1: newVal, field2, newVal}})
: finds all matching documents then updates their values based on arg2.
III. Nested documents
1. Example
{
name: "Wimpy Kid",
author: {
lastname: "Kinney",
firstname: "Jeff" ,
}
genre: ["Comedy", "Fiction"],
reader: [
{name: "Vivian", age: 18},
{name: "Irene", age: 20}
]
}
1. Querying arrays
- { field : value } : value is the exact array to match, including the order of the elements.
- { array field: { operator1: value1, ... } }
// dress collection
colors: ['red', 'black']
// height collection
heights: [10, 15.25]
// match an array with exact order
db.dress.find({colors:['red','black']})
// match an array without exact order
db.dress.find({colors: {$all: ['red','black'] }})
// query an array for an element
db.dress.find({colors: 'red' })
db.heights.find({ heights: {$gt: 10, $lt:12}})
// query an array by array length
db.heights.find({ heights: {$size: 3}})
All rights reserved