MongoDB Cheat Sheet - Tóm lược câu lệnh tương tác trong mongodb

03cd82 2024

MongoDB Cheat Sheet

Show All Databases

Hiển thị danh sách các CSDL có trong hệ thống

show dbs

Show Current Database

Hiển thị CSDL hiện tại bạn đang làm việc tên là gì

db

Create Or Switch Database

Chuyển sang làm việc với một CSDL hoặc nếu chưa có thì tạo mới. VD làm việc với CSDL tên là books

use books

Drop

Xóa CSDL

db.dropDatabase()

Create Collection

Tạo mới một Collection (tương ứng 1 bảng trong SQL)

db.createCollection('posts')

Show Collections

Hiển thị danh sách các Collection (bảng) có trong CSDL hiện tại

show collections

Insert Row

Chèn thêm 1 dòng (1 document) vào collection (bảng) . Dữ liệu đưa vào là 1 đối tượng theo cấu trúc đối tượng của javascript.

db.posts.insert({
  title: 'Post One',
  body: 'Body of post one',
  category: 'News',
  tags: ['news', 'events'],
  user: {
    name: 'John Doe',
    status: 'author'
  },
  date: Date()
})

Insert Multiple Rows

Chèn thêm nhiều dòng trong bảng. Dữ liệu đưa vào sẽ là một mảng (array) các đối tượng.

db.posts.insertMany([
  {
    title: 'Post Two',
    body: 'Body of post two',
    category: 'Technology',
    date: Date()
  },
  {
    title: 'Post Three',
    body: 'Body of post three',
    category: 'News',
    date: Date()
  },
  {
    title: 'Post Four',
    body: 'Body of post three',
    category: 'Entertainment',
    date: Date()
  }
])

Get All Rows

Lấy ra danh sách các document (dòng) trong collection (bảng). Mặc định sẽ trả về 20 bản ghi đầu tiên.

db.posts.find()

Get All Rows Formatted

Lấy ra danh sách bản ghi và có định dạng sẵn về cách trình bày

db.posts.find().pretty()

Find Rows

Tìm kiếm dòng theo điều kiện, tham số truyền vào là 1 đối tượng, các thuộc tính là các cột muốn lọc dữ liệu

db.posts.find({ category: 'News' })

Sort Rows

Sắp xếp dữ liệu kết quả tìm kiếm bằng hàm sort(). Điều kiện sắp xếp là tên cột với giá trị là số dương 1 thì tăng, số âm 1 thì giảm

# asc
db.posts.find().sort({ title: 1 }).pretty()
# desc
db.posts.find().sort({ title: -1 }).pretty()

Count Rows

Đếm số dòng bằng hàm count()

db.posts.find().count()
db.posts.find({ category: 'news' }).count()

Limit Rows

Giới hạn số dòng sẽ trả về khi lấy danh sách bằng cách dùng hàm limit()

db.posts.find().limit(2).pretty()

Chaining

Vừa giới hạn, vừa sắp xếp

db.posts.find().limit(2).sort({ title: 1 }).pretty()

Foreach

Sử dụng lệnh lặp để điều khiển tùy chỉnh kết quả tìm kiếm

db.posts.find().forEach(function(doc) {
  print("Blog Post: " + doc.title)
})

Find One Row

Tìm kiếm và chỉ trả về 1 dòng

db.posts.findOne({ category: 'News' })

Find Specific Fields

db.posts.find({ title: 'Post One' }, {
  title: 1,
  author: 1
})

Update Row

db.posts.update({ title: 'Post Two' },
{
  title: 'Post Two',
  body: 'New body for post 2',
  date: Date()
},
{
  upsert: true
})

Update Specific Field

db.posts.update({ title: 'Post Two' },
{
  $set: {
    body: 'Body for post 2',
    category: 'Technology'
  }
})

Increment Field ($inc)

db.posts.update({ title: 'Post Two' },
{
  $inc: {
    likes: 5
  }
})

Rename Field

db.posts.update({ title: 'Post Two' },
{
  $rename: {
    likes: 'views'
  }
})

Delete Row

db.posts.remove({ title: 'Post Four' })

Sub-Documents

db.posts.update({ title: 'Post One' },
{
  $set: {
    comments: [
      {
        body: 'Comment One',
        user: 'Mary Williams',
        date: Date()
      },
      {
        body: 'Comment Two',
        user: 'Harry White',
        date: Date()
      }
    ]
  }
})

Find By Element in Array ($elemMatch)

db.posts.find({
  comments: {
     $elemMatch: {
       user: 'Mary Williams'
       }
    }
  }
)

Add Index

db.posts.createIndex({ title: 'text' })

Text Search

db.posts.find({
  $text: {
    $search: "\"Post O\""
    }
})

Greater & Less Than

Điều kiện so sánh, vd: Tìm bài viết có cột views (số lượt xem) như ở bên dưới.

db.posts.find({ views: { $gt: 2 } })  // tìm bài viết có số lượt view (views) lớn hơn ($gt) 2
db.posts.find({ views: { $gte: 7 } }) // lớn hơn hoặc bằng
db.posts.find({ views: { $lt: 7 } })   // bé hơn
db.posts.find({ views: { $lte: 7 } })  // bé hơn hoặc bằng
Nguồn: zezo.dev