Return latest record from subdocument in Mongodb

前端 未结 3 1647
-上瘾入骨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.

    0 讨论(0)
  • 2021-01-24 11:15

    Queries in MongoDB do not return subdocuments (or, as in your case, subdocuments of subdocuments). They match and return the the documents in the collection. The documents' shape can be changed a bit by projection, but it's limited. If you want to find the latest tag commonly, you probably want to make your documents represent tags. Having an array in an array is generally a bad idea in MongoDB, too.

    If this is an uncommon operation, and one that doesn't need to be particularly fast, you can use an aggregation:

    db.modules.aggregate([
        { "$unwind" : "$svn_branches" },
        { "$unwind" : "$svn_branches.tags" },
        { "$sort" : { "svn_branches.tags.updated_at" : -1 } },
        { "$group" : { "_id" : "$_id", "latest_tag" : { "$first" : "$svn_branches.tags" } } }
    ])
    
    0 讨论(0)
  • 2021-01-24 11:33

    I needed to find the last entry of subdocuments and I managed to make it to work with the $slice projection operator: mondodb.com > $slice (projection)

    db.modules.find({_id:'ui', 'svn_branches.branch':'Rocky'}, 
                    { 'svn_branches.tags': {$slice:-1} } )
    

    I had only one level, if this doesn't work, please let me know.

    0 讨论(0)
提交回复
热议问题