arrow_back
Back

MongoDB queries: databases, collections, and CRUD

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

Database operations

db.version()    // Server version
db.help()       // List of commands
db.stats()      // Stats

List and select databases:

show dbs            // List databases
use <database>      // Switch to a database (creates it on first write)

Collections

db.createCollection('posts')    // Create collection
show collections                // List collections

Document count:

db.<collectionName>.count({ /* query */ })

Insert documents

db.<collectionName>.insertOne({ /* ... */ })
db.<collectionName>.insertMany([{ /* ... */ }, { /* ... */ }])

Find documents

db.<collectionName>.find({ /* query */ })
db.<collectionName>.findOne({ /* query */ })

db.<collectionName>.find({})        // All documents
db.<collectionName>.findOne({})     // First document

Helpers

Chain these after find():

  • sort()
  • limit()
  • skip()

Examples:

.find({}).limit(5)
.find({}).skip(2)                 // Skip the first two
.find({}).sort({ comments: 1 })   // ASC
.find({}).sort({ comments: -1 })  // DESC

Default sort order is by _id ascending.

Query operators

  • $or, $and
  • $in, $nin
  • $eq, $ne
  • $lt, $gt
  • $regex

Examples:

db.getCollection('posts').find({ comments: { $gt: 0 } })
db.getCollection('posts').find({
    $and: [
        { comments: { $lt: 5 } },
        { comments: { $gt: 0 } }
    ]
})
db.getCollection('posts').find({
    tags: {
        $in: ['programming', 'coding']
    }
})

Update documents

db.<collectionName>.updateOne(<query>, <update>, <options>)
db.<collectionName>.updateMany(<query>, <update>, <options>)

Update operators (second argument):

  • $set
  • $rename
  • $unset
  • $currentDate
  • $inc — increment
  • $addToSet

$set

db.posts.updateOne(
    { postId: 2452 },
    { $set: { shared: true } }
);

$unset

Removes fields. Example — remove quantity and instock from the first product where sku is "unknown":

db.products.updateOne(
    { sku: 'unknown' },
    { $unset: { quantity: '', instock: '' } }
)

$inc

Increments a numeric field (here by 1):

db.posts.updateOne(
    { postId: 4352 },
    { $inc: { comments: 1 } }
);

Delete documents

db.<collectionName>.deleteOne({ /* query */ })
db.<collectionName>.deleteMany({ /* query */ })

Examples:

db.getCollection('posts').deleteOne({ postId: NumberInt(1111) })
db.getCollection('posts').deleteMany({ title: { $exists: false } })
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

MongoDB indexes: single-field and compound

arrow_forward