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

การคิวรีอาร์เรย์ใน MongoDB เพื่อดึงค่าเฉพาะ

ใช้ $unwind, $match, $project ใน Aggregate

แยกอาร์เรย์ด้วย $unwind กรองด้วย $match แล้วเลือกฟิลด์ด้วย $project

สร้างข้อมูลตัวอย่าง

> db.demo761.insertOne({
    "details": [ { "student": { "FullName": "Chris Brown" } } ]
});
> db.demo761.insertOne({
    "details": [ { "student": { "FullName": "Chris Taylor" } } ]
});

แสดงข้อมูลทั้งหมด

> db.demo761.find();

ผลลัพธ์:

{ "_id" : ObjectId("5eb034d15637cd592b2a4af1"), "details" : [ { "student" : { "FullName" : "Chris Brown" } } ] }
{ "_id" : ObjectId("5eb034d25637cd592b2a4af2"), "details" : [ { "student" : { "FullName" : "Chris Taylor" } } ] }

คิวรีค้นหาและแสดงเฉพาะ FullName = "Chris Taylor"

> db.demo761.aggregate([
    {'$unwind':'$details'},
    {'$match': { 'details.student.FullName':'Chris Taylor' }},
    {'$project': { 'details.student.FullName': 1, '_id': 0 }}
])

ผลลัพธ์

{ "details" : { "student" : { "FullName" : "Chris Taylor" } } }