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

MongoDB Aggregation และ Projection: การประมวลผลและเลือกฟิลด์

ใช้ $project ร่วมกับ aggregate()

$project ใน aggregation pipeline ใช้ส่งเอกสารพร้อมฟิลด์ที่ระบุไปยังขั้นตอนถัดไป

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

> db.demo762.insertOne({
    "_id" : { "userId":101, "userName":"Chris" },
    "countryName" : "US",
    "details" : [
        { "Name" : "Robert", "DueDate" : "2020-04-10" },
        { "Name" : "Robert", "DueDate" : "2020-04-09" },
        { "Name" : "Robert", "DueDate" : "2020-03-06" }
    ]
});

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

> db.demo762.find();

ผลลัพธ์:

{ "_id" : { "userId" : 101, "userName" : "Chris" }, "countryName" : "US", "details" : [ { "Name" : "Robert", "DueDate" : "2020-04-10" }, { "Name" : "Robert", "DueDate" : "2020-04-09" }, { "Name" : "Robert", "DueDate" : "2020-03-06" } ] }

คิวรี Aggregate: จับคู่ user, unwind details, เรียงตาม DueDate, จำกัด 2 รายการล่าสุด

> db.demo762.aggregate([
    { "$match": { "_id": { "$eq": { userId:101, userName:"Chris" }} } },
    { "$unwind": "$details" },
    { "$sort": { "details.DueDate": 1 } },
    { "$group": {
        "_id": "$_id",
        "details": { "$push": "$details" },
        "countryName": { "$first": "$countryName" }
    }},
    { "$project": { "details": { "$slice": ["$details", 2] }, "countryName": 1 } }
]).pretty();

ผลลัพธ์: เอกสาร user พร้อม 2 รายการ DueDate เก่าสุด

{ "_id" : { "userId" : 101, "userName" : "Chris" }, "countryName" : "US", "details" : [ { "Name" : "Robert", "DueDate" : "2020-03-06" }, { "Name" : "Robert", "DueDate" : "2020-04-09" } ] }