如何使用MongoDB平面子文档中的字段

时间:2015-03-03 21:34:31

标签: mongodb

我有以下集合,其中每个文档都有一个包含文档快照的数组。

{
        "_id" : 1,
        "field1" : "value1",
        "field2" : "value2",
        "field3" : "value3",
        "version" : [
                {
                        "v" : 3,
                        "element" : {
                                "field1" : "value1",
                                "field2" : "value2",
                                "field3" : "value3"
                        }
                },
                {
                        "v" : 1,
                        "element" : {
                                "field1" : "value11",
                                "field2" : "value12",
                                "field3" : "value13"
                        }
                }
        ]
}
{
        "_id" : 2,
        "field1" : "valueA",
        "field2" : "valueB",
        "field3" : "valueC",
        "version" : [
                {
                        "v" : 2,
                        "element" : {
                                "field1" : "valueA",
                                "field2" : "valueB",
                                "field3" : "valueC"
                        }
                }
        ]
}

通过下一步操作,我将检索特定快照中的文档状态:

db.test.aggregate( 
    { $unwind: '$version' }, 
    { $match: { 'version.v': { $lte: 3 } }}, 
    { $group: { '_id' : '$_id', 'element' : { $first: '$version.element'}} })

结果是:

{
        "_id" : 2,
        "element" : {
                "field1" : "value1",
                "field2" : "value2",
                "field3" : "value3"
        }
}
{
        "_id" : 1,
        "element" : {
                "field1" : "valueA",
                "field2" : "valueB",
                "field3" : "valueC"
        }
}

我的问题是,是否有任何方法可以平滑子文档中的字段'元素'像这样显示在顶层:

{
        "_id" : 2,
        "field1" : "value1",
        "field2" : "value2",
        "field3" : "value3"
}
{
        "_id" : 1,
        "field1" : "valueA",
        "field2" : "valueB",
        "field3" : "valueC"
}

1 个答案:

答案 0 :(得分:2)

您可以使用$project

> db.test.aggregate(
   { $unwind: '$version' }, 
   { $match: { 'version.v': { $lte: 3 } }},
   { $group: { '_id' : '$_id', 'element' : { $first: '$version.element'}} },
   {$project : { "field1" : "$element.field1",
                 "field2" : "$element.field2",
                 "field3" : "$element.field3" } } ).pretty();

这会产生您的预期输出。

但是,我建议考虑使用一个单独的集合,其中每个版本都有自己的文档,用于我能想到的大多数用例。请记住,反复增长的文档对性能有害,并且与直接查询相比,读取复杂性相对较高......