有人能告诉我,请如果有可能通过一个集合迭代,检查字段值是否包含集合字符串,并返回MongoDB聚合集合字符串?
如果我有一个这样的集合:
[
{
"foo": "a",
"name": "tomas",
},
{
"foo": "a",
"name": "herbas",
},
]
如下所示:
(TOM, Herb)
我想得到的结果是:
{'name_abbr': 'TOM'}, {'name_abbr': 'HERB'}
我已经玩了$setDifference和$regexMatch,但不能弄清楚如何返回包含集合的给定字段值的集合子字符串。
提前感谢您的帮助。
我不确定你的预期结果到底是什么,但如果我理解正确,你想检查你的集合中哪些字符串可以作为一个正则表达式匹配到你的文档之一name
,你可以这样做:
db.collection.aggregate([
{$addFields: {
results: {
$reduce: {
input: inputSet,
initialValue: [],
in: {$concatArrays: [
"$$value",
{$cond: [
{$regexMatch: {input: "$name", regex: "$$this", options: "i"}},
[{name_abbr: "$$this"}],
[]
]
}
]
}
}
}
}
},
{$group: {_id: 0, res: {$push: "$results"}}},
{$set: {
_id: "$$REMOVE",
res: {$reduce: {
input: "$res",
initialValue: [],
in: {$concatArrays: ["$$value", "$$this"]}
}
}
}
}
])
看看它在操场的例子中是如何工作的
这回答了你的问题吗?