在聚合管道中匹配子文档键。

huangapple go评论92阅读模式
英文:

Match on subdocument key in aggregation pipeline

问题

我需要将 categoryId(2)与 categoryTypes 中的键(2)匹配。基本上,我需要说:
$match: { categoryId: categoryTypes } 谢谢!

英文:

Given that I have a hash subdocument within my document, how can I match a value - categoryId (itself added using $addFields) - to the sub-document key - categoryTypes - in my aggregation pipeline:
ex:

{
   _id: $someId,
   categoryId: 2,
   categoryTypes: {
     1: "hello world",
     2: "something else",
     3: "still more stuff"
   }
}

I need to match categoryId (2) to key in categoryTypes (2). In essence I need to say:

$match: { categoryId: categoryTypes }

Thanks!

答案1

得分: 0

一种选择是使用$objectToArray

db.collection.aggregate([
  {$set: {allKeys: {$objectToArray: "$categoryTypes"}}},
  {$match: {$expr: {$in: [{$toString: "$categoryId"}, "$allKeys.k"]}}},
  {$unset: "allKeys"}
])

playground example上查看其运行效果。

英文:

One option is to use $objectToArray:

db.collection.aggregate([
  {$set: {allKeys: {$objectToArray: "$categoryTypes"}}},
  {$match: {$expr: {$in: [{$toString: "$categoryId"}, "$allKeys.k"]}}},
  {$unset: "allKeys"}
])

See how it works on the playground example

答案2

得分: 0

好的,这就是我翻译好的部分:

原来比我最初想的简单:

1- 首先将哈希变成一个数组,生成一个子文档,看起来像这样 ARRAY: [ "0": {...}, "1": {...}, ...]

// 这发生在 $addFields 阶段
categories: { "$objectToArray": "$categoryTypes"}

2- 然后在我的 project 阶段,我做了以下操作:

category: {
    $filter: {
        input: '$categories',
        as: 'item',
        cond: {$eq: ['$$item.k', "$categoryId"]}
    }}

希望这对其他可能正在寻找类似解决方案的人有所帮助。

英文:

Well it turns out that's simpler than I originally thought:

1- First changed the hash into an array which produced a subdocument which looks like ARRAY: [ "0": {...}, "1": {...}, ...]

// this is happening in $addFields stage
categories: { "$objectToArray": "$categoryTypes"}

2- Then in my project stage I did:

category: {
    $filter: {
        input: '$categories',
        as: 'item',
        cond: {$eq: ['$$item.k', "$categoryId"]}
    }}

Hope this helps others who may be looking for a similar solution.

huangapple
  • 本文由 发表于 2023年4月11日 02:25:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定