Blog

Truy vấn Document trong MongoDB

Last updated on November 1st, 2022 at 04:45 pm

Phương thức find() trong MongoDB

Để truy vấn dữ liệu từ Collection trong MongoDB, bạn cần sử dụng phương thức find().

Cú pháp

Cú pháp cơ bản của phương thức find() là như sau:

>db.COLLECTION_NAME.find()

Phương thức find() sẽ hiển thị tất cả Document ở dạng không có cấu trúc (hiển thị không theo cấu trúc nào).

Phương thức pretty() trong MongoDB

Để hiển thị các kết quả theo một cách đã được định dạng, bạn có thể sử dụng phương thức pretty().

Cú pháp

>db.mycol.find().pretty()

Ví dụ

>db.mycol.find().pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

Ngoài phương thức find(), chúng ta còn có phương thức findOne() sẽ chỉ trả về một Document.

Truy vấn trong MongoDB mà tương đương mệnh đề WHERE trong RDBMS

Để truy vấn Document dựa trên một số điều kiện nào đó, bạn có thể sử dụng các phép toán sau:

Phép toánCú phápVí dụMệnh đề WHERE tương đương
Equality{<key>:<value>}db.mycol.find({“by”:”tutorials point”}).pretty()where by = ‘tutorials point’
Less Than{<key>:{$lt:<value>}}db.mycol.find({“likes”:{$lt:50}}).pretty()where likes < 50
Less Than Equals{<key>:{$lte:<value>}}db.mycol.find({“likes”:{$lte:50}}).pretty()where likes <= 50
Greater Than{<key>:{$gt:<value>}}db.mycol.find({“likes”:{$gt:50}}).pretty()where likes > 50
Greater Than Equals{<key>:{$gte:<value>}}db.mycol.find({“likes”:{$gte:50}}).pretty()where likes >= 50
Not Equals{<key>:{$ne:<value>}}db.mycol.find({“likes”:{$ne:50}}).pretty()where likes != 50

AND trong MongoDB

Cú pháp

Trong phương thức find(), nếu bạn truyền nhiều key bằng cách phân biệt chúng bởi dấu phảy (,), thì MongoDB xem nó như là điều kiện AND. Cú pháp cơ bản của AND như sau:

>db.mycol.find({key1:value1, key2:value2}).pretty()

Ví dụ

Ví dụ sau hiển thị tất cả loạt bài hướng dẫn (tutorials) được viết bởi ‘tutorials point’ có title là ‘MongoDB Overview’

>db.mycol.find({"by":"tutorials point","title": "MongoDB Overview"}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

Mệnh đề WHERE tương đương với ví dụ trên sẽ là ‘ where by=’tutorials point’ AND title=’MongoDB Overview’ ‘. Bạn có thể truyền bất kỳ số cặp key-value nào trong mệnh đề find.

OR trong MongoDB

Cú pháp

Để truy vấn Document dựa trên điều kiện OR, bạn cần sử dụng từ khóa $or. Cú pháp cơ bản của OR như sau:

>db.mycol.find(
   {
      $or: [
	     {key1: value1}, {key2:value2}
      ]
   }
).pretty()

Ví dụ

Ví dụ sau sẽ hiển thị tất cả loạt bài hướng dẫn (tutorials) được viết bởi ‘tutorials point’ hoặc có title là ‘MongoDB Overview’

>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

Sử dụng AND và OR

Ví dụ

Ví dụ sau hiển thị các Document mà có các like lớn hơn 100 và có title là hoặc ‘MongoDB Overview’ hoặc bởi là ‘tutorials point’. Mệnh đề WHERE trong truy vấn SQL tương đương là ‘where likes>10 AND (by = ‘tutorials point’ OR title = ‘MongoDB Overview’)’

>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

Nguồn: Internet

Chúng tôi chuyên cung cấp những khóa học về Phân tích dữ liệu, đăng ký ngay để nhận được tư vấn chi tiết lộ trình dành riêng cho bạn nhé!

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    https://jmspc.ac.in/ Tren Komunitas Urban Jakarta: Permainan Papan Klasik ke Adaptasi Mahjong Digital Cara kerja fitur ubin emas terhadap pengguna agar tetap menatap layar berjam-jam Menghindari godaan kombinasi parlay panjang yang sering berujung pada penyesalan Menemukan ritme bermain yang pas agar hobi hiburan digital tidak sampai mengganggu produktivitas kerja Wild West Gold vs Wild Bounty Showdown mana yang sebenarnya lebih ramah untuk dimainkan pemula alasan mengapa fitur scatter hitam selalu sukses memanipulasi rasa penasaran pemain mahjong ways fakta di balik kemenangan pertama dan dampaknya pada pengambilan keputusan lanjutan Kenapa Player Jakarta Kembali Melirik Mahjong Ways 2 di Tengah Gempuran Tren Game Baru Lainnya Alasan Utama Gates of Olympus 1000 Mendadak Kuasai Obrolan Warung Kopi Jakarta Bulan Ini Gema Hiburan yang Menentukan Arah Ritme Permainan Edukasi Cara Kerja Simbol Olympus yang Bikin Banyak Orang Ketagihan Mencoba Apa Perbedaan Mekanika Antara Olympus Klasik dan Versi Upgrade Terbarunya Analis Sebut Mahjong Jadi Pelopor Game Online Masa Kini Pemain Baccarat Jakarta Jadi Perbincangan, Bicara Kemenangan hingga Kesuksesan Cara Mengelola Saldo Harian Agar Sesi Bermain PG Soft Tetap Terkendali Dari Data ke Historis, Menggagas Formasi untuk Hasil Parlay Banyak yang Salah Paham Soal Cara Kerja RTP Baccarat Meski Sering Dimainkan Tiap Hari Rahasia di Balik Pola Ubin Emas yang Bikin Pemain PG Soft Susah Lepas dari Layar Sering Viral di Media Sosial, Begini Sebenarnya Algoritma Gates of Olympus 1000 Bekerja Ternyata Ini Alasan Fitur Scatter Hitam Mahjong Ways Mendadak Ramai Dibicarakan Bulan Ini slot4d slotsensa slot gacor https://www.jmsit.ac.in/placement/ suhubet slot4d https://fabritec.pe/asesor.php https://kibf.pk/ slot4d slot gacor https://www.jms.ac.in/admission-procedure/ slot gacor slot luar negeri slot4d slot gacor 4d totogacor slot4d slot4d slot gacor slot gacor slot gacor https://promo-sign.com/ slot4d demo slot slot thailand slot4d https://www.ugelhuaylas.edu.pe/ slot4d slot4d slot4d https://dulsa.com/ slot4d https://fabritec.pe/see/corporacion/ slot4d https://waterco.co.id/pompa-kolam-renang/ https://cliffcrestinn.com/rates/ https://www.bhagwati.ac.in/academics/ https://seteilhas.com.br/site/ https://umgeg.com/ https://www.paracasoverland.com.pe/ slot gacor slot gacor 4d https://amcstoneandcabinets.com/ totogacor slot gacor wd jutaan https://spingharkabul.edu.af/ https://lpmi.handayani.ac.id/surveyB https://www.jalwadancecompany.com/x-2-3-bhangra-dancers/ https://gaesasa.com/tienda/ https://impactocontable.co/servicios-tributarios-pago-de-impuestos/ https://spingharkabul.edu.af/published-papers/ https://littlebigcat.com/ slot4d https://gaesasa.com/sobre-gaesa/ https://warmihuasi.org/proyectos/ https://coppercoat.com.br/ slot gacor https://www.jetfloweurope.com/ slot gacor https://www.norsal-eg.com/ slot4d https://subhkirancapital.com/ slot gacor https://spingharkabul.edu.af/stomatology/ https://www.balinanny-babbyhire.com/pricing/ https://cliffcrestinn.com/historic-places-to-stay-in-santa-cruz-ca/ https://moalem24.com/ https://pps.handayani.ac.id/ toto 4d https://ekklesiahouses.com/ https://happyspring.com/ https://hitchparts.com/ https://praisevibration.com/ https://bolsecol.com/ https://centrobienser.com/ slot gacor https://www.jalwadancecompany.com/ https://solnascentealimentos.com.br/ https://www.homeofenglish.edu.kh/ https://www.balinanny-babbyhire.com/ https://warmihuasi.org/ https://gaesasa.com/blog/ https://gaesasa.com/shop/ https://www.blccampus.edu.lk/ https://warmihuasi.org/enlaces/ https://www.uniparconstrutora.com.br/tour/ https://solnascentealimentos.com.br/blog/ https://www.balinanny-babbyhire.com/faq/ https://adibintanpermata.com/shop/ slot4d totogacor Slot Gacor situs gacor 4D situs gacor slot4d SLOT4D slot4d slot gacor 4d Slot Thailand slot4d Slot Thailand Slot Thailand Slot Gacor Maxwin Slot Thailand Slot Thailand