Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Tạo và hiển thị database mới trong MongoDB

Tạo database mới

MongoDB tạo database **lười biếng (lazy creation)**: database chỉ thực sự được tạo khi có dữ liệu đầu tiên được ghi vào (tạo collection + insert document).

Cú pháp chuyển đổi/tạo database:

use tenDatabaseMoi

Hiển thị danh sách database

show dbs

Chỉ hiển thị database đã có dữ liệu (đã tạo collection + insert).

Ví dụ minh họa

1. Chuyển sang database mới

> use onlinecustomertracker
switched to db onlinecustomertracker

2. Tạo collection và insert document đầu tiên (database mới lúc này mới thực sự tạo)

> db.example.insert({Value: 10});
WriteResult({ "nInserted" : 1 })

3. Xem document vừa insert

> db.example.find();
{ "_id" : ObjectId("5e9dafade3c3cd0dcff36a4f"), "Value" : 10 }

4. Liệt kê tất cả database

> show dbs;
MyDB                   0.000GB
admin                  0.000GB
config                 0.000GB
local                  0.000GB
onlinecustomertracker  0.000GB
test                   0.006GB

Database onlinecustomertracker giờ xuất hiện trong danh sách.

Lưu ý

  • Chỉ use db chưa tạo database vật lý - cần ghi dữ liệu.
  • Database admin, config, local là database hệ thống.
  • Đổi database hiện tại: use tenDbKhac.
  • Xem database hiện tại: db (trong shell).