请考虑以下几千个对象的MongoDB集合:
{
_id: ObjectId("xxx")
FM_ID: "123"
Meter_Readings: Array
0: Object
Date: 2011-10-07
Begin_Read: true
Reading: 652
1: Object
Date: 2018-10-01
Begin_Reading: true
Reading: 851
}
为阵列输入了错误的2018年密钥,需要将其重命名为“ Begin_Read”。我有一个列表,该列表使用具有错误密钥的所有对象的另一个聚合。数组中的对象没有_id值,因此很难选择。我当时想我可以遍历集合,找到错误读数的数组索引,并使用对象的_id对键执行$rename
。
我正在尝试获取数组的索引,但似乎无法正确选择它。以下是我的汇总:
[
{
'$match': {
'_id': ObjectId('xxx')
}
}, {
'$project': {
'index': {
'$indexOfArray': [
'$Meter_Readings', {
'$eq': [
'$Meter_Readings.Begin_Reading', True
]
}
]
}
}
}
]
其结果始终为-1,我认为这意味着我的表达式必须是错误的,因为预期结果将为1。
我正在为此脚本使用Python(也可以使用javascript),如果有更好的方法(可能是过滤器?),我可以选择其他方法,就像我想出的那样。
答案 0 :(得分:0)
我自己解决了这个问题。我对汇总很了解,但由于某种原因(一个无法正常工作)而需要研究另一个领域:
{
'$project': {
'index': {
'$indexOfArray': [
'$Meter_Readings.Water_Year', 2018
]
}
}
}
我学到的是在数组中找到对象的方法,您只需在$indexOfArray
方法的数组标识符中引用它即可。我希望这可以帮助其他人。