0

我正在尝试在 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”的第二个数组条目“Value”字段中存储的值,并将其用作新字段的值。

使用 MongoDB Shell,命令

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]} 

访问包含所需信息的对象。但是之后如何访问“价值”的内容呢?

任何帮助将不胜感激!:)

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

4

3 回答 3

0

根据上述描述,请尝试在 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
        }

    ]
); 
于 2017-06-01T13:38:02.497 回答
0

这是另一个解决方案。我是 MongoDB 的新手,但这似乎可行:

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

该解决方案似乎也取消了第二次投影。我也很想听听 MongoDB 技术人员的意见,该解决方案存在本质上的问题。

于 2018-01-18T20:38:00.513 回答
0

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

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

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

"newName" : "$newName_temp.Value"

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

于 2017-06-08T06:50:59.147 回答