仅返回投影数组子文档中的特定字段 [英] Return only specific fields from projection array sub-document

查看:71
本文介绍了仅返回投影数组子文档中的特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 $ $elemMatch 预测.我试图弄清楚如何只返回一个子集 投影数组的字段,但我似乎无法弄清楚.

I'm looking at MongoDB's documentation on the $ and $elemMatch projections. I'm trying to figure out how to return only a subset of a projection array's fields, but I cannot seem to figure it out.

相关帖子:

  • I am not trying to perform a $slice from mongodb aggregation framework - Fetch first document's field of the nested array.

我也不是试图从仅在mongo投影中返回数组值中的子文档吗?仍然需要顶部文档中的某些字段.

Nor am I trying to flatten the sub-document from Return only array value in mongo projection because I still want some fields from the top document.

说我在test集合中有以下文档:

Say I have the following documents in the test collection:

{
    "_id": "A",
    "array": [
        {"key": 1, "name": "foo", "data": {}},
        {"key": 2, "name": "bar", "data": {}}
    ],
    "extra": {}
},
{
    "_id": "B",
    "array": [
        {"key": 3, "name": "spam", "data": {}},
        {"key": 4, "name": "eggs", "data": {}}
    ],
    "extra": {}
}

我实际上要执行的查询是:

The query I effectively want to perform is:

db.test.findOne({"array.key": 1}, {"array.$.name": 1, "extra": 1})

我希望它只返回name key1的数组.例如,

Which I would expect it to only return name under the sub-document in the array where key was 1. E.g.,

{
    "_id": "A",
    "array": [
        {"name": "foo"}
    ],
    "extra": {}
}

但是,如果我执行该查询,则会得到以下信息:

But if I perform that query, I get this instead:

{
    "_id": "A",
    "array": [
        {"key": 1, "name": "foo", "data": {}}
    ],
    "extra": {}
}

与执行查询相同:

db.test.findOne({"array.key": 1}, {"array.$": 1, "extra": 1})

我还尝试了以下操作,结果相同:

I've also tried the following which results in the same:

db.test.findOne({"array.key": 1}, {"array.$": 1, "array.name": 1, "extra": 1})

是否有一种方法只返回array.$的字段的子集 而不是整个子文档?

Is there a way to only return a subset of the fields for array.$ instead of the whole sub-document?

推荐答案

您是否专门尝试在不使用聚合的情况下做到这一点?

Are you specifically trying to do this without using aggregate?

db.test.aggregate([{$unwind:"$array"},
                   {$match:{"array.key":1}},
                   {$project:{"array.name":1, extra:1}}])

这篇关于仅返回投影数组子文档中的特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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