从 Mongodb 中的子文档返回最新记录 [英] Return latest record from subdocument in Mongodb

查看:64
本文介绍了从 Mongodb 中的子文档返回最新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想从子文档中返回最新插入的文档.我希望能够返回带有 54a1845def7572cd0e3fe288

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 54a1845def7572cd0e3fe288

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

So I far I have this query but it returns all values in the tags array.

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

Mongodb 数组:

Mongodb array:

{
"_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 中,在数组中包含数组通常也是一个坏主意.

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" } } }
])

这篇关于从 Mongodb 中的子文档返回最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆