1

我正在使用 mongo 聚合框架,但我根本无法弄清楚一些术语。最特别的是,在某些示例中,参考 $project 处于“包含模式”。我还听说 _id 在相关上下文中被选择为“隐含”。谁能澄清一下?

http://docs.mongodb.org/manual/reference/aggregation/project/

db.article.aggregate(
    { $project : {
        title : 1 ,
        stats : {
            pv : "$pageViews",
            foo : "$other.foo",
            dpv : { $add:["$pageViews", 10] }
        }
    }}
);


This projection includes the title field and places $project into “inclusive” mode. Then, it creates the stats documents with the following fields:
4

1 回答 1

1

_id 被选择“隐式”

当您进行预测时,您必须明确指定所有字段:

> db.a.find()
{ "_id" : ObjectId("51c8744a1c0a41d783d77431"), "a" : 1, "b" : 2, "c" : 3 }
> db.a.aggregate({$project:{a:1}})
{
    "result" : [
        {
            "_id" : ObjectId("51c8744a1c0a41d783d77431"),
            "a" : 1
        }
    ],
    "ok" : 1
}

在这里,您在结果文档中仅包含“a”,所有其他字段均已删除。唯一的区别是_id字段,它始终包含在内,但您可以明确将其关闭:

> db.a.aggregate({$project:{a:1, _id:0}})
{ "result" : [ { "a" : 1 } ], "ok" : 1 }

$project 处于“包容模式”

这很简单:如果您希望某些字段按原样包含在结果文档,您可以输入类似{a:1}的内容,它只是说{a:'$a'} 的快捷方式

于 2013-06-24T16:39:07.640 回答