我正在尝试在 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”。