1. 摘要
天翼云TELDB提供的MongoDB數據庫服務允許用戶通過SHELL環境執行核心數據庫操作。用戶可以連接到MongoDB實例、選擇和創建數據庫、插入和查詢文檔、更新和刪除數據、創建索引以優化查詢。這些基本操作指南涵蓋了MongoDB SHELL環境下的數據操作和管理任務,旨在幫助用戶高效地使用天翼云TELDB的MongoDB服務進行數據存儲和管理。
2.操作指南
2.1 插入文檔
insertOne
db.products.insertOne( { item: "card", qty: 15 } );
insertMany
db.products.insertMany( [ { _id: 10, item: "large box",
qty: 20 }, { _id: 11, item: "small
box", qty: 55 }, { _id: 12, item: "medium box", qty: 30 }
] );
Insert
db.collection.insert( <document or array of
documents>, { writeConcern: <document>, ordered:
<boolean> } )
2.2 刪除文檔
deleteOne
db.orders.deleteOne( { "_id" : ObjectId("563237a41a
4d68582c2509da") } );
db.orders.deleteOne( { "expirationTime" : { $lt:
ISODate("2015-11-01T12:40:15Z") } } );
deleteMany
db.orders.deleteMany( { "client" : "Crude Traders
Inc." } );
remove
db.collection.remove( <query>, <justOne> )
2.3 使用 Drop 刪除集合
使用 DB.<COLLECTION>.Drop()來刪除一個集合,集合中的全部文檔都會被刪除,集合相關的索引也會被刪除。
db.colToBeDropped.drop()
使用 DB.dropDatabase()來刪除數據庫,數據庫相應文件也會被刪除,磁盤空間將被釋放。
use tempDB
db.dropDatabase()
show collections // No collections
show dbs // The db is gone
2.4 使用 Find 查詢數據文檔
Find 是 MongoDB 的基礎查詢命令,Find 返回數據的游標(Cursor)
db.movies.find( { "year" : 1975 } ) //單條件查詢
db.movies.find( { "year" : 1989, "title" : "Batman" } ) //
多條件 and 查詢
db.movies.find( { $or: [{"year" : 1989}, {"title" :
"Batman"}] } ) //多條件 or 查詢
db.movies.find( { $and : [ {"title" : "Batman"}, {
"category" : "action" }] } ) // and 查詢
db.movies.find( { "title" : /^B/} ) //按正則表達式查找
2.5 SQL 查詢條件對照
a = 1 -> {a: 1}
a <> 1 -> {a: {$ne: 1}}
a > 1 -> {a: {$gt: 1}}
a >= 1 -> {a: {$gte: 1}}
a < 1 -> {a: {$lt: 1}}
a <= 1 -> {a: {$lte: 1}}
a = 1 AND b = 1 -> {a: 1, b: 1}或{$and: [{a: 1}, {b:
1}]}
a = 1 OR b = 1 -> {$or: [{a: 1}, {b: 1}]}
a IS NULL -> {a: {$exists: false}}
a IN (1, 2, 3) -> {a: {$in: [1, 2, 3]}}
2.6 查詢操作符
$lt: 存在并小于
$lte: 存在并小于等于
$gt: 存在并大于
$gte: 存在并大于等于
$ne: 不存在或存在但不等于
$in: 存在并在指定數組中
$nin: 不存在或不在指定數組中
$or: 匹配兩個或多個條件中的一個
$and: 匹配全部條件
2.7 更新操作
Update 操作需要執行參數,參數包括查詢參數、更新參數。
// insert data
db.movies.insert( [
{ "title" : "Batman", "category" : [ "action", "adventure"
], "imdb_rating" : 7.6, "budget" : 35 }, { "title" :
"Godzilla", "category" : [ "action", "adventure", "sci-fi"
], "imdb_rating" :
6.6 }, { "title" : "Home Alone", "category" : [ "family",
"comedy" ], "imdb_rating" : 7.4
}
] )
db.movies.update( { "title" : "Batman" }, { $set : {
"imdb_rating" : 7.7 } } )
$Push: 增加一個對象到數組底部
$PushAll: 增加多個對象到數組底部.
$Pop: 從數組底部刪除一個對象
$Pull: 如果匹配指定的值或條件,從數組中刪除相應的
對象.
$PullAll: 如果匹配列表中的任意值,從數組中刪除相應
的對象.
$PullAll: 如果匹配列表中的任意值,從數組中刪除相應
的對象
$AddToSet: 如果不存在則增加一個值到數組