从Mongodb中的子文档返回最新记录

从Mongodb中的子文档返回最新记录,mongodb,Mongodb,假设我想从子文档返回最新插入的文档。我希望能够使用54a1845def7572cd0e3fe288的\u id返回标记数组中的第二条记录 到目前为止,我有这个查询,但它返回标记数组中的所有值 db.modules.findOne({_id:"ui","svn_branches.branch":"Rocky"},{"svn_branches.$":1}) Mongodb阵列: { "_id" : "ui", "svn_branches" : [ { "updated_a

假设我想从子文档返回最新插入的文档。我希望能够使用
54a1845def7572cd0e3fe288的
\u id
返回标记数组中的第二条记录

到目前为止,我有这个查询,但它返回标记数组中的所有值

db.modules.findOne({_id:"ui","svn_branches.branch":"Rocky"},{"svn_branches.$":1})
Mongodb阵列:

{
"_id" : "ui",
"svn_branches" : [ 
    {
        "updated_at" : ISODate("2013-06-12T20:48:17.297Z"),
        "branch" : "Rocky",
        "revision" : 0,
        "tags" : [ 
            {
                "_id" : ObjectId("54a178b8ef7572d30e3fe288"),
                "commit_message" : "r277 | ssmith | 2015-02-11 17:43:23 -0400 (Wed, 11 Feb 2015)",
                "latest_tag" : "20150218r1_6.32_abc",
                "revision" : 1,
                "tag_revision_number" : "280",
                "updated_at" : ISODate("2015-02-18T19:54:54.062Z")
            }, 
            {
                "_id" : ObjectId("54a1845def7572cd0e3fe288"),
                "commit_message" : "r271 | sam | 2dskjh\n",
                "latest_tag" : "20150218r2_6.32_abc",
                "revision" : 2,
                "tag_revision_number" : "281",
                "updated_at" : ISODate("2015-02-19T19:54:54.062Z")
            }
        ]
    }
]
}

MongoDB中的查询不会返回子文档(或者,在您的情况下,返回子文档中的子文档)。它们匹配并返回集合中的文档。通过投影可以稍微改变文档的形状,但这是有限的。如果要查找最新的标记,可能需要使文档表示标记。在MongoDB中,在数组中使用数组通常也是一个坏主意

如果这是一个不常见的操作,并且不需要特别快,则可以使用聚合:

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" } } }
])
简单解 假设我们有一个
类别
作为
文档
项目
作为
子文档

// find document from collection
const category = await Category.findOne({ _id:'$hec453d235xhHe4Y' });

// fetch last index of sub-document
const lastItemIndex = category.items.length - 1;
        
// here is the last item of sub-document
console.log(category.items[lastItemIndex]);

由于mongodb在最后一个索引中插入了最新的子文档,因此我们需要找到最新子文档的最后一个索引。

我需要找到子文档的最后一个条目,并设法使其与
$slice
投影操作符一起工作:

我只有一个级别,如果这不起作用,请告诉我

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