我的 MongoDB 集合中有以下文档:
{
"name": "name",
"items": [
{
"raw": { ... }
"processed": { ... }
},
{
"raw": { ... }
"processed": { ... }
}
]
}
我正在尝试聚合/查询数据库,以便获得这些项目:
[
{"raw": { ... }},
{"raw": { ... }}
]
我现在正在使用聚合框架,但我卡在了要排除外部文档字段的部分。
我当前的查询是:
db.mycollections.aggregate([
{ $unwind: "$items" },
{ $project: { "items.raw": 1 } }
])
它返回:
[
{"items: {"raw": { ... }}},
{"items: {"raw": { ... }}}
]
有没有办法只返回上述查询中的子文档?
最佳答案
如果您使用 unwind
将聚合编写为:
db.mycollections.aggregate({"$unwind":"$items"})
然后输出看起来像:
{ "_id" : ObjectId(), "name" : "name", "items" : { "raw" : {... }, "processed" : { ... } } }
{ "_id" : ObjectId() , "name" : "name", "items" : { "raw" : { ...}, "processed" : { ...} } }
$project将仅包含指定字段的文档传递到管道中的下一个阶段。指定的字段可以是输入文档中的现有字段或新计算的字段。
并且您使用 items.raw
将 $project
作为现有字段传递,因此不要将此现有字段传递给项目,而是使用 expression新字段名称为 raw
并将聚合更改为
db.mycollections.aggregate({"$unwind":"$items"},{"$project":{"raw":"$items.raw"}})
有关详细信息,请查看 mongo aggregation pipeline
关于mongodb - 仅返回 MongoDB 中的子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30619484/