Mongo db อย่างโปร (part 2— ค้นหาอย่างง่าย).
วันนี้จะมาอธิบายวิธีการสอบถามข้อมูล(query) เบื้องต้น(อย่าง่ายสุดๆ) ใน mongodb โดยวิธี query จะกระทำผ่านสิ่งที่เรียกว่า Shell Command
คำสั่ง find()
ค้นหา
db.getCollection(‘users’).find();
คำสั่งนี้จะเหมือนกับ sql command
select * from users;
Tips : db.getCollection(‘users’) สามารถเขียนย่อได้เป็น db.users
ค้นหาด้วยเงื่อนไข
ถ้าเราต้องการค้นหาโดยมีเงื่อนไขให้ใส่ดังนี้
db.users.find({user_name:’mongoInw’});
คำสั่งนี้จะเหมือนกับ sql command
select * from users where user_name = ‘mongoInw’;
ค้นหาหลายเงื่อนไข
db.users.find({name:’justin’, user_type:’admin’});
คำสั่งนี้จะเหมือนกับ sql command
select * from users where (name = ‘justin’ and user_type = ‘admin’);
Tips: ถ้าต้องการเงื่อนไขที่ซับซ้อนกว่านี้ เช่น or, notโปรดดู Logical Query Operators (เดี๋ยวสอน)
ค้นหาโดยเอาแค่บางฟิลด์ (ทำ projection)
db.users.find({user_name:’mongoInw’}, {id:1,email:1});
คำสั่งนี้จะเหมือนกับ sql command
select id, email from users where user_name = mongoInw;
Tips : เราสามารถ projection โดยไม่เอาบางฟิลด์ได้โดย db.users.find({user_id:1}, {email:0}); เท่ากับเอาทุกฟิลด์ ยกเว้น email
ค้นหาและนับจำนวน
db.users.find({user_type:’admin’}).count();
คำสั่งนี้จะเหมือนกับ sql command
select count(id) from users where user_type = ‘admin’;
distinct
db.users.distinct( “status” )
คำสั่งนี้จะเหมือนกับ sql command
SELECT DISTINCT(status)
FROM users
จัดเรียง
db.users.find().sort({name:-1});
โดย 1
คือ ascending และ -1
คือ descending
Tips : คุณสามารถใส่ 0 ได้ แต่ mongo จะ error และด่ากลับมา
Limit and Skip
db.users.find().skip(10).limit(5);
Tips : สามารถค้นหา limit=1 ตลอดได้โดยใช้ findOne() แทน find()
รวมทุกอย่างเข้าด้วยกัน
db.users.find({name:’justin’, user_type:’admin’},{name:1,id:1}).skip(0).limit(5).sort({name:-1});
ตู้ม..
จบตอน 2
ตอนต่อไปเราจะมาพูดถึงการ query ที่ซับซ้อนมากขึ้น เช่น json ซ้อนกัน, json array, json array ของ object, json ซ้อนกัน และซ้อนกัน และก็ซ้อนกันอีก รอติดตามชมครับ..