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

Nested Document Value Search ใน MongoDB

การค้นหาค่าใน Nested Document

สำหรับการค้นหาค่า ให้ใช้ $match ใน MongoDB

สร้าง Collection พร้อมข้อมูล

> db.demo648.insertOne(
...     {
...         StudentInformation:
...         [
...             {
...                 Name:"John",
...                 CountryName:"US"
...             },
...             {
...                 Name:"David",
...                 CountryName:"AUS"
...             },
...             {
...                 Name:"Chris",
...                 CountryName:"US"
...             },
...             {
...                 Name:"Robert",
...                 CountryName:"UK"
...             }
...         ]
...     }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5e9c8b286c954c74be91e6f5") }

แสดงเอกสารทั้งหมด

> db.demo648.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e9c8b286c954c74be91e6f5"), "StudentInformation" : [
    { "Name" : "John", "CountryName" : "US" },
    { "Name" : "David", "CountryName" : "AUS" },
    { "Name" : "Chris", "CountryName" : "US" },
    { "Name" : "Robert", "CountryName" : "UK" }
] }

คิวรีค้นหา CountryName = US

> db.demo648.aggregate([
...     { $unwind: "$StudentInformation" },
...     { $match: { "StudentInformation.CountryName": "US" } },
...     { $project: {_id: 0}}
... ])

ผลลัพธ์:

{ "StudentInformation" : { "Name" : "John", "CountryName" : "US" } }
{ "StudentInformation" : { "Name" : "Chris", "CountryName" : "US" } }