Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีเชื่อมต่อ MongoDB Collection ผ่าน Command Line

การเชื่อมต่อและ Query MongoDB Collection ผ่าน Command Line (Mongo Shell)

ใช้คำสั่ง db.collectionName.find() ใน Mongo Shell เพื่อ Query ข้อมูลจาก Collection (Table)

ขั้นตอนการเชื่อมต่อ

  1. เข้า Mongo Shell: mongo หรือ mongo --host localhost --port 27017
  2. เลือก Database: use databaseName
  3. Query Collection: db.collectionName.find()

ตัวอย่างการใช้งาน

> use sample;
switched to db sample

> db;
sample

> show collections;

รายการ Collections ใน Database sample:

arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation

Query Collection: userInformation

> db.userInformation.find();

ผลลัพธ์:

{ 
    "_id" : ObjectId("5c6a765964f3d70fcc9147f5"), 
    "Name" : "John", 
    "Age" : 30, 
    "isStudent" : false, 
    "Subjects" : [ "Introduction to java", "Introduction to MongoDB" ] 
}

คำสั่งพื้นฐานใน Mongo Shell

คำสั่งคำอธิบาย
show dbsแสดงรายการ Database ทั้งหมด
use <dbname>สลับไปใช้ Database ที่ระบุ
dbแสดง Database ปัจจุบัน
show collectionsแสดง Collection ทั้งหมดใน DB ปัจจุบัน
db.collection.find()Query ข้อมูลทั้งหมดใน Collection
db.collection.findOne()Query เอกสารแรกที่เจอ
db.collection.find().pretty()แสดงผลสวยงาม (Formatted JSON)
db.collection.count()นับจำนวนเอกสาร (Deprecated ใช้ countDocuments())

ตัวอย่าง Query เพิ่มเติม

// Query ด้วยเงื่อนไข
> db.userInformation.find({ "Age": { $gt: 25 } });

// Query และ Project เฉพาะฟิลด์ที่ต้องการ
> db.userInformation.find({}, { "Name": 1, "Age": 1, "_id": 0 });

// Limit ผลลัพธ์
> db.userInformation.find().limit(5);

// Sort
> db.userInformation.find().sort({ "Age": -1 });

การเชื่อมต่อจาก Command Line โดยตรง (ไม่เข้ Shell)

# Query เดียวจาก Terminal
mongo sample --eval 'db.userInformation.find().forEach(printjson)'

# Export เป็น JSON
mongoexport --db sample --collection userInformation --out users.json

# Import จาก JSON
mongoimport --db sample --collection userInformation --file users.json

Connection String (URI Format)

# Localhost
mongodb://localhost:27017/sample

# With Authentication
mongodb://username:password@localhost:27017/sample

# Replica Set
mongodb://host1:27017,host2:27017/sample?replicaSet=rs0

Mongo Shell เป็น Interactive JavaScript Environment สามารถเขียน Script, Loop, Function ได้เต็มรูปแบบ