ในการดึงเอกสาร ให้ใช้ $in แทน $และใน MongoDB ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.demo83.insertOne( ... { ... "Details":[ ... { ... "Name":"Chris", ... "Subject":[ ... "MySQL", ... "MongoDB" ... ] ... }, ... { ... "Name":"David", ... "Subject":[ ... "Java", ... "C" ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2bfd2271bf0181ecc422a3") } > db.demo83.insertOne( ... { ... "Details":[ ... { ... "Name":"Bob", ... "Subject":[ ... "C++", ... "Python" ... ] ... }, ... { ... "Name":"John", ... "Subject":[ ... "Spring", ... "Hibernate" ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2bfd4571bf0181ecc422a4") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo83.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e2bfd2271bf0181ecc422a3"), "Details" : [ { "Name" : "Chris", "Subject" : [ "MySQL", "MongoDB" ] }, { "Name" : "David", "Subject" : [ "Java", "C" ] } ] } { "_id" : ObjectId("5e2bfd4571bf0181ecc422a4"), "Details" : [ { "Name" : "Bob", "Subject" : [ "C++", "Python" ] }, { "Name" : "John", "Subject" : [ "Spring", "Hibernate" ] } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อค้นหาเอกสารโดยใช้ $in -
> db.demo83.find({ "Details" : { "$elemMatch" : {"Name" :"Chris" , "Subject":{"$in":["MongoDB"]}}}});
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e2bfd2271bf0181ecc422a3"), "Details" : [ { "Name" : "Chris", "Subject" : [ "MySQL", "MongoDB" ] }, { "Name" : "David", "Subject" : [ "Java", "C" ] } ] }