arrays - 在 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),如果有更好的方法来做到这一点(也许是过滤器?),我愿意接受替代方案,这正是我想出的。
解决方案
我自己解决了这个问题。我与聚合很接近,但出于某种原因需要查看另一个字段,但该字段不起作用:
{
'$project': {
'index': {
'$indexOfArray': [
'$Meter_Readings.Water_Year', 2018
]
}
}
}
我学到的是在数组中找到一个对象,你可以在$indexOfArray
方法的数组标识符中引用它。我希望这可能对其他人有所帮助。
推荐阅读
- snowflake-cloud-data-platform - 使用 SHOW_INITIAL_ROWS 参数创建的雪花流在选择时引发错误
- r - R:如果条目以字母结尾,则将上面一或两行的信息粘贴到空单元格中
- python - 在 Windows 上: :Go 构建失败并出现错误 ./go-python.h:4:10: fatal error: Python.h: No such file or directory #include "Python.h"
- python - 如何根据id的groupby从先前的测量中创建一个标记(1 - 体重减轻;0 - 相同体重a)体重减轻(8%或更多)的列?
- python - 如何在 Python 中使用带有用户输入和循环的制表模块?
- c# - 画圆点
- xml - xslt 2.0 替换为 xml 结构
- java - 如何解决抛出 NoUniqueBeanDefinitionException 的子类 Bean?
- java - ControllerAdvice 不处理抛出的异常
- sql - 两个字段的四个值:ab ;bc,如何合并成一个字段 abc