首页 > 解决方案 > 在 MongoDB 中对对象数组中的项目使用 $rename

问题描述

考虑以下几千个对象的 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),如果有更好的方法来做到这一点(也许是过滤器?),我愿意接受替代方案,这正是我想出的。

标签: arrayspython-3.xmongodb

解决方案


我自己解决了这个问题。我与聚合很接近,但出于某种原因需要查看另一个字段,但该字段不起作用:

{
 '$project': {
   'index': {
      '$indexOfArray': [
          '$Meter_Readings.Water_Year', 2018
                    ]
                }
            }
        }

我学到的是在数组中找到一个对象,你可以在$indexOfArray方法的数组标识符中引用它。我希望这可能对其他人有所帮助。


推荐阅读