仅返回MongoDB中的子文档

时间:2015-06-03 11:58:01

标签: mongodb

我的MongoDB集合中有以下文档:

{
   "name": "name",
   "items": [
        {
            "raw": { ... }
            "processed": { ... }
        },
        {
            "raw": { ... }
            "processed": { ... }
        }
   ]
}

我正在尝试聚合/查询数据库,以便获取这些项目:

[
 {"raw": { ... }},
 {"raw": { ... }}
]

我现在正在使用聚合框架,但是我被困在我要排除外部文档字段的部分。

我目前的查询是:

db.mycollections.aggregate([
    { $unwind: "$items" },
    { $project: { "items.raw": 1 } }
])

它返回:

[
 {"items: {"raw": { ... }}},
 {"items: {"raw": { ... }}}
]

有没有办法只从上面的查询中返回子文档?

1 个答案:

答案 0 :(得分:1)

如果您使用unwind编写聚合作为:

db.mycollections.aggregate({"$unwind":"$items"})

然后输出如下:

{ "_id" : ObjectId(), "name" : "name", "items" : { "raw" : {... }, "processed" : { ... } } }
{ "_id" : ObjectId() , "name" : "name", "items" : { "raw" : { ...}, "processed" : { ...} } }

$project将仅包含指定字段的文档传递到管道中的下一个阶段。指定的字段可以是输入文档或新计算字段中的现有字段。

并且您使用$projectitems.raw作为现有字段传递,因此不会将此现有字段传递给项目,而是使用新字段名称为raw的{​​{3}}并更改您的聚合如

db.mycollections.aggregate({"$unwind":"$items"},{"$project":{"raw":"$items.raw"}})

有关详细信息,请查看 expression