通过动态字段路径从嵌入式文档中添加字段

通过动态字段路径从嵌入式文档中添加字段

本文介绍了MongoDB 聚合:通过动态字段路径从嵌入式文档中添加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个聚合管道并且被困在舞台上.此时我有一个格式如下的文档:

I have an aggregation pipeline and am stuck on a stage. At this point I have a document in the following format:

{
  _id:ObjectId(5e3d326637df7e4dda73ec22),
  levelName:"Level 1",
  levelNames: {
    "Level 1":"5e567993b6ed4b7b4d2c044d"
    "Level 2":"5e567996a7826d45f836dfa3"
    "Level 3":"5e5679991f515a01c73e9006"
  }
}

我想添加一个 $addField/$set 阶段,它为我提供 levelNames 对象中条目的 ID 值,其键与根文档的 levelName 属性匹配.

and I want to add an $addField/$set stage which gives me the ID value of the entry in the levelNames object with a key matching the levelName property of the root document.

我一直在尝试使用某种动态字段路径 ($concat: ["levelNames.", "$levelName"]) 但没有运气.这是我的 $addField 阶段:

I've been trying to use some sort of dynamic field path ($concat: ["levelNames.", "$levelName"]) but have had no luck. This is my $addField stage:

/**
 * newField: The new field name.
 * expression: The new field expression.
 */
{
  currentLevelId: {
    $let: {
      vars: {
        levelPath: {
          $concat: ["levelNames.", "$levelName"]
        }
      },
      in: {
        currentLevelId: "$$levelPath"
      }
    }
  }
}

我得到的结果是:

{
  _id:ObjectId(5e3d326637df7e4dda73ec22),
  levelName:"Level 1",
  levelNames: {
    "Level 1":"5e567993b6ed4b7b4d2c044d"
    "Level 2":"5e567996a7826d45f836dfa3"
    "Level 3":"5e5679991f515a01c73e9006"
  }
  currentLevelId: {
    currentLevelId:"levelNames.Level 1"
  }
}

我试图让 currentLevelId 的结果为5e567993b6ed4b7b4d2c044d",所以我想要的输出是:

I'm trying to get the result of currentLevelId to be "5e567993b6ed4b7b4d2c044d", so my desired output is:

{
  _id:ObjectId(5e3d326637df7e4dda73ec22),
  levelName:"Level 1",
  levelNames: {
    "Level 1":"5e567993b6ed4b7b4d2c044d"
    "Level 2":"5e567996a7826d45f836dfa3"
    "Level 3":"5e5679991f515a01c73e9006"
  },
  currentLevelId: "5e567993b6ed4b7b4d2c044d"
}

有什么办法可以实现吗?

Is there a way this can be achieved?

推荐答案

使用这个:

db.collection.aggregate([
   { $set: { data: { $objectToArray: "$levelNames" } } },
   {
      $set: {
         currentLevelId: {
            $arrayElemAt: ["$data.v", { $indexOfArray: ["$data.k", "$levelName"] }]
         }
      }
   },
   { $unset: "data" }
])

蒙古游乐场

这篇关于MongoDB 聚合:通过动态字段路径从嵌入式文档中添加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:39