จะจัดเรียงอาร์เรย์ของเอกสารรับเนื้อหาและความยาวในการรวม mongodb ได้อย่างไร

สมมติว่าฉันมีสคีมาดังที่แสดงด้านล่าง:

user = {
    id:'an id'
    username: 'some username'
}
post = {
    id:'an id'
    creater: 'some user id'
    postText: 'some text'
}
comment = {
    id:'an id'
    idOfPostThisCommentBelongsTo: 'some id'
    idOfCommenter: 'some id',
    commentText: 'some text' 
}

ด้านล่างนี้คือ mongodb ของฉันผ่านฟังก์ชันรวมพังพอน:

Post.aggregate([
        {$match:{"_id" : 'idOfThePost'}},
        {$lookup:{from:"users",localField:"creater",foreignField:"_id",as:"userWhoCreatedThisPost"}},
        {$unwind:"$userWhoCreatedThisPost"},
        {$lookup:{from:"comments",localField:"_id",foreignField:"idOfPostThisCommentBelongsTo",as:"comments"}},

        // unwind, sort by date, grouping them back
        {$unwind: {
            "path": '$comments',
            "preserveNullAndEmptyArrays": true
        }},
        {$sort: {'comments.createdAt': -1}}, 
        {$group: {
            _id: '$_id', 
            postText:{$first: '$postText'},
            //how can I get the length of the comments' array????
            'comments': {$push: '$comments'}
        }}, 

        // without the group pipeline this is how I can get the number of comments(see below)
        // but when I try using the group pipeline(above) and project pipeline(below) 
        // and the aggregation doesn't work 
        {$project:{
            numberOfComments:{$size:'comments'},
        }}

ฉันสามารถรับความคิดเห็นและจัดเรียงตามวันที่ได้ แต่ฉันติดอยู่กับการพยายามที่จะได้รับความยาวของความคิดเห็นทั้งหมด

ฉันรู้ว่าฉันสามารถใช้ $first เพื่อรับค่าของเอกสารก่อนหน้าได้ ฉันได้ลองแสดงความคิดเห็นแล้ว: {$first: {$size: $comments}} แต่มันไม่ทำงาน

ฉันจะรับขนาดของอาร์เรย์ความคิดเห็นในขณะที่ยังคงเรียงลำดับอาร์เรย์ตามวันที่ในขณะที่ยังคงรับค่าของโพสต์และเอกสารผู้ใช้ได้อย่างไร (ดูตัวอย่างด้านล่าง)

{
    _id: 5e5faae00e77ab07f0a7c661,
    userWhoPostedThePost: 'object with user details'
    postText: 'post text',
    comments: [ // sorted by date in descending order
              { /** comment content*/},
              { /** comment content*/}
    ]
}

person YulePale    schedule 06.03.2020    source แหล่งที่มา


คำตอบ (1)


โดยพื้นฐานแล้วคุณสามารถเปลี่ยนกลุ่มของคุณให้รวมเป็น 1 ทุกครั้งที่พบความคิดเห็น บางสิ่งเช่นนี้:

$group: {
    _id: '$_id', 
    'comments': {$sum: 1}
}
person Guiller    schedule 06.03.2020