Pymongo:如何访问投影中嵌套数组中对象的字段值?

Pymongo: How to access the field value of an object in a nested array in a Projection?

我正在尝试在 pymongo(3.3.0、Python 3.6.0、MongoDB 3.2)中编写投影代码。

原始数据的形式大致为:

{
    "_id" : ObjectId("592fd5ac1aee05abb6104912"),
    "Results" : {
            "SomeData" : 1234,
            "ResultAllPoints" : {
                "MyArray" : [
                     {
                         "Value" : 0.5,
                         "Result" : 1,
                     },
                     {
                          "Value" : 1.5,
                          "Result" : 1,
                     }
                     {
                          "Value" : 1.7,
                          "Result" : 1,
                     }
                ]
            }
    }
}

我想访问 "MyArray" 的 second 数组条目字段 "Value" 中存储的值,并将其用作新字段的值.

使用MongoDBShell,命令

db.my_collection.findOne().Results.ResultAllPoints.myArray[1].Value

准确地给出了我希望在生成的集合中拥有的价值。

然而,在我的投影代码中,

{"newName" : "$Results.ResultAllPoints.myArray[1].Value"}

也不

{"newName" : "$Results.ResultAllPoints.myArray.1.Value"}

正在工作。在第一种情况下,"newName" 根本没有出现在结果中,第二种情况导致空数组作为 "newName" 的内容。

我已经知道我可以使用

{"$arrayElemAt": [ "$Results.ResultAllPoints.MyArray", 1]} 

访问包含所需信息的对象。但是之后如何访问"Value"的内容呢?

如有任何帮助,我们将不胜感激! :)

编辑:这不是 Retrieve only the queried element in an object array in MongoDB collection 的副本,因为我事先不知道 "Value" 的内容,因此不能使用“$elemMatch”。

根据上述描述请尝试在MongoDB shell

中执行以下聚合查询
db.my_collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $match: { "_id" : ObjectId("592fd5ac1aee05abb6104912")}
        },

        // Stage 2
        {
            $unwind: "$Results.ResultAllPoints.MyArray"
        },

        // Stage 3
        {
            $skip: 1
        },

        // Stage 4
        {
            $limit: 1
        }

    ]
); 

虽然我希望有一个更简单的解决方案,但我通过在管道中添加第二个投影找到了解决方法。第一个包含我的所有其他投影项目及其新名称并投影包含数组 "myArray":

"newName_temp" : {"$arrayElemAt": [ "$Results.ResultAllPoints.MyArray", 1 ]}

第二个投影复制第一个投影中的所有项目以保留它们,然后通过

访问"Value"内容
"newName" : "$newName_temp.Value"

这篇文章很长,所以我总是乐于接受更好的解决方案!

这是另一种解决方案。我是 MongoDB 的新人,但这似乎有效:

db.junk.aggregate(    
    [
        {
            $project: {
              newName: {
                $let: {
                  vars: {
                    x: {
                      $arrayElemAt: ["$Results.ResultAllPoints.MyArray", 1]
                    }
                  },
                  in: "$$x.Value"      
                }
              }
            }
        },
    ] 
);

这个解决方案似乎也取消了第二个投影。我也很想听听 MongoDB 方面的专家的意见,解决方案是否存在本质上的错误。