These commands are for MongoDB shell and not for the mongo db Node.js driver or mongoose package.
The examples here uses this sample dataset. Please, follow the instructions to setup the sample collection.
This is quick start for developers who want to a be up and running in no time.
Refer to the original documentation for extensive examples and guidance.
- Setup the environment
- Show All Databases
- Show Current Database
- Create Or Switch Database
- Drop a database
- Create Collection
- Show Collections
- Insert Row
- Insert Multiple Rows
- Important notes about the Find() Methods
- Get All Rows
- Get All Rows Formatted
- Find Specific Rows
- Chaining of Methods
- Sort Rows
- Count Rows
- Limit Rows
- Find Nested Objects
- Find Array by values
- Find By Element in Array ($elemMatch)
- Find Multiple using Operator And | OR
- Find using Operator - Not
- Find using Operator - IN and Not IN
- Text Search and Add Index
- Find using Regex pattern matching
- Find using operator Greater & Less Than
- Find and Show Specific Fields
- findAndModify()
- Find One Row > And (update | Replace | Delete)
- Foreach
- Update(Replace) All Rows
- Update(modify) Specific Field
- Updating Sub-Documents
- Increment Field ($inc)
- Rename Field
- Delete Row/Document
show dbs
db
db.getName()
use acme
db.dropDatabase()
db.createCollection('posts')
show collections
db.getCollectionNames()
db.posts.insert({
'firstName' : 'Arvinda',
'lastName' : 'de Silva',
'email' : 'de [email protected]',
'age' : 40,
'active' : false,
'tags' : [ 'migration', 'connect', 'Multi-channelled', 'maximize'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
{
'user' : 'arvidr30',
'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
'date' : Date()
}
]
})
db.posts.insertMany([
{
'firstName' : 'Salem',
'lastName' : 'Gonzalo',
'email' : '[email protected]',
'age' : 40,
'active' : false,
'tags' : [ 'migration', 'complexity', 'maximize', 'Drives'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
{
'user' : 'salloG123',
'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
'date' : Date()
}
]
},
{
'firstName' : 'Rodney',
'lastName' : 'de Souza',
'email' : '[email protected]',
'age' : 40,
'active' : false,
'tags' : [ 'Integration', 'Belize Dollar', 'Checking Account'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
{
'user' : 'rodeySou123',
'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
'date' : Date()
}
]
}
])
-
to find based on a specific criteria we can make use of operator like , $all, $in ,$nin, $not, $regex, along with the and, or and nor operator, check relevant section and documentation.
-
Most of the find methods have the last argument containing options, you have to check the documentation on each. However,here is an example
db.posts.find({firstName:'John'}, {firstName:1 , lastName:1})
The second object {firstName:1 , lastName:1}
is the projection. See some explantion below.
Here are the most common options with explanations:
Option | Explanation |
---|---|
projection <document> | A subset of fields to return. |
sort <documet> | Specifies a sorting order for the documents matched by the filter |
upsert boolean | When true,Creates a new document if no documents match the filter.NB:To avoid multiple upserts, ensure that the filter fields are uniquely indexed. |
returnNewDocument boolean | When true, returns the updated/inserted(upsert above) document instead of the original document. |
- if the find method performs some update operation, there may be an upsert option, check the explanation the options table.
- There is also chaining of methods available. So you can process the results further, after they are found. Check Chaining of Methods section
Here is a simple example:
- Find post with firtName = John
- Show firstName and LastName fields only
- Then sort the result by lastName descending.
db.posts.find({firstName:'John'}, {_id:0,firstName:1 , lastName:1}).sort({lastName:-1})
db.posts.find()
db.find().pretty()
db.posts.find({ firstName: 'John'})
- Here results are found, we start chainging by
- limiting the result to show 2 documents
- and sorting it by firstName descending
- then prettifying the result
db.posts.find().limit(2).sort({ firstName: 1 }).pretty()
# asc
db.posts.find().sort({ lastName: 1 }).pretty()
# desc
db.posts.find().sort({ lastName: -1 }).pretty()
db.posts.find().count()
db.posts.find({ firstName: 'John' }).count()
db.posts.find().limit(2).pretty()
db.posts.find({ 'comments.user':'Lucio67'})
Some examples:
Exactly the same array
db.posts.find( { tags: [ "collaborative", "Product" ] } )
Find posts with tags containing a specified(one) value, besides other values:
db.posts.find( { tags: "Product" } )
Find posts with tags containing either values, i.e. either "collaborative" OR "Product"
db.posts.find({ tags: { $in: [ "collaborative", "Product" ]}} )
Find posts with tags containing both values, i.e. either "collaborative" AND "Product":
db.posts.find( { tags: {$all : [ "collaborative", "Product" ] }} )
We can specify conditions as well. Check the documentation for complete examples. Here are some examples, though not related to our collection "posts" but showing what is possible:
- single conditions
- Multiple conditions
- Multiple conditions using $elemMatch
- Finding by array index position
- Finding by array size
db.inventory.find( { dim_cm: { $gt: 25 } } )
db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )
db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )
db.inventory.find( { "dim_cm.1": { $gt: 25 } } )
db.inventory.find( { "tags": { $size: 3 } } )
db.posts.find({
comments: {
$elemMatch: {
user: 'Mary Williams'
}
}
}
)
AND and OR are both array of Objects
$and: [... {}]
$or: [... {}]
Here is an example: Find all document which have
- firstName OR lastName as John And
- is Either active OR age is Greater Than 45
- then display only these Fields
- firstName, lastName , age, active
- Then prettify the result
db.posts.find({
$and : [
{ $or : [ { firstName :'John' }, { lastName :'John' } ] },
{ $or : [ { active : true }, { age : { $gt : 45 } } ] }
]
} ,{firstName:1,lastName:1, active:1, age:1}).pretty()
Using the implicit AND (directly Specifying the or statements)
db.posts.find({
$or : [ {firstName: 'John'},{lastName: 'John'} ],
$or : [ {active : true }, { age : { $gt : 45 } }]
}, {firstName:1,lastName:1, active:1, age:1}).pretty()
All the posts that are not active, active is not true:
db.posts.find( {"active": { $not: /^t.*/}}).pretty();
All the posts where the age is 30,40,45 and similarly for not in:
db.posts.find({"age" : { $in : [30,40,45]}}).count()
db.posts.find({"age" : { $nin : [30,40,45]}}).count()
db.posts.createIndex({ firstName: 'text' })
db.posts.find({
$text: {
$search: '\'Post O\''
}
})
Regex can be pretty daunting at times, so here are a few links to work with:
Monog Regex Documenation examples
- In regexr, we put test data on the multiline, just make sure to enable the multiline option and global option accordingly if needed
Example with regexr
All the posts where the firstName starts with the alphabet A
So,put in the text area some examples Alpa Allo Asgard
Then enable global and multiline options.
In the regex field type : ^A.*
We will be able to see the result of selected.
Now put it in the mongo Db:
db.posts.find( {"firstName": { $regex: /^A.*/}}).pretty();
BTW, in the above example in Regexr, we thought of multiline as separate document with firsName represented on each line.
If you have some large field in the document like db.posts.post, which is multiline , and you want to search in this multiline field , we have option like { $regex: /^A.*/m}
, notice the m. checkout the documentation.
db.posts.find({ age: { $gt: 45} })
db.posts.find({ age: { $gte: 40 } })
db.posts.find({ age: { $lt: 35 } })
db.posts.find({ age: { $lte: 35 } })
projection is what(Fields) to return
db.collection.find(query,projection)
db.posts.find({ firstName: 'John' }, {
_id:0,
firstName: 1,
age: 1
})
For each of these example run the db.posts.find({})
and just pick some object_ids to work with.
This returns the first document according to the natural order which reflects the order of documents on the disk.
db.posts.findOne({ active: true })
db.posts.findOneAndDelete({_id : ObjectId("5ea221bca66626db52fe02b8")})
db.posts.findOneAndReplace({_id : ObjectId("5ea221bca66626db52fe02b9")},
{
'firstName' : 'Ruppet2',
'lastName' : 'Magrega2',
'email' : '[email protected]',
'age' : 35,
'active' : false,
'tags' : [ 'Integration', 'Belize Dollar', 'Checking Account'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
{
'user' : 'ruppetMag345',
'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
'date' : Date()
}
]
} ,
{returnNewDocument : true}
)
db.posts.findOneAndUpdate()
db.posts.find().forEach(function(doc) {
print('User: ' + doc.firstName + ' ' + doc.lastName)
})
db.posts.find({firstName : 'John'}).forEach(printjson);
Check update(modify) Specific Field for updating specific fields.
This will update(replace) with the new document, all the rows that it matched(found).
If the new document is missing fields , then all the matched rows will be missing the fields as it replaces.
db.posts.update({ {_id : ObjectId("5ea221bca66626db52fe02b9") },
{
'firstName' : 'Ruppet2',
'lastName' : 'Magrega2',
'email' : '[email protected]',
'age' : 35,
'active' : false,
'tags' : [ 'Integration', 'Belize Dollar', 'Checking Account'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
{
'user' : 'ruppetMag345',
'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
'date' : Date()
}
]
},
{
upsert: true
})
Update active to true where , firstName = John and age is between 35 and 40
db.posts.update(
{
'firstName' : 'John',
age' :{$gte : 35, $lte : 40}
}
,
{
$set: {
active: true
}
})
db.posts.update({ title: 'Post One' },
{
$set: {
comments: [
{
body: 'Comment One',
user: 'Mary Williams',
date: Date()
},
{
body: 'Comment Two',
user: 'Harry White',
date: Date()
}
]
}
})
db.posts.update({ title: 'Post Two' },
{
$inc: {
likes: 5
}
})
Rename the field active to available for all the documents.
db.posts.update({},
{
$rename: {
active: 'available'
}
})
db.posts.remove({ title: 'Post Four' })