Return latest record from subdocument in Mongodb

前端 未结 3 1648
-上瘾入骨i
-上瘾入骨i 2021-01-24 10:45

Let\'s say i want to return the latest inserted document from the subdocument. I want to be able to return the second record within the tags array w/ the _id of

3条回答
  •  广开言路
    2021-01-24 11:13

    One Simple Solution

    Let say we have a category as a document and items as a subdocument.

    // find document from collection
    const category = await Category.findOne({ _id:'$hec453d235xhHe4Y' });
    
    // fetch last index of sub-document
    const lastIndexOfSubDoc: number = category.items.length - 1;
            
    // here is the last item of sub-document
    console.log(category.items[lastIndexOfSubDoc]);
    

    as mongodb inserted the latest sub-document at last index, so we need to find the last index for the latest sub-doc.

提交回复
热议问题