英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论