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

ตั้งเงื่อนไขใน MongoDB nested document


สมมติว่าเราต้องการหาเอกสารที่มีค่ามากกว่าค่าเฉพาะ สำหรับเรื่องนี้ ให้ใช้ dot notation ใน nested document และตั้งเงื่อนไขด้วย $gt มาดูตัวอย่างและสร้างคอลเลกชันพร้อมเอกสารกันก่อน

> db.demo688.insert( ... { ... information:{id:1,details:[ ...    {otherDetails:{ ...       values:75 ...       } ...    } ... ] ... } ... } ... ) WriteResult({ "nInserted" : 1 }) > db.demo688.insert({ ... information: ... { ... id:2, ... details: ... [ ...    {otherDetails:{ ...       values:78 ...    } ... } ... ] ... } ... } ... ) WriteResult({ "nInserted" : 1 })

แสดงเอกสารทั้งหมดจากคอลเลกชันด้วยเมธอด find()

> db.demo688.find();

จะได้ผลลัพธ์ดังนี้

{ "_id" : ObjectId("5ea57986a7e81adc6a0b3965"), "information" : { "id" : 1, "details" : [ { "otherDetails" : { "values" : 75 } } ] } } { "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }

คำสั่งสำหรับเข้าถึง MongoDB nested document

> db.demo688.find({"information.details.otherDetails.values":{$gt:75}});

จะได้ผลลัพธ์ดังนี้

{ "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }