在MongoDB中串联重复字符串值时忽略这些值 [英] ignore duplicated string values while concatinating them in mongodb
本文介绍了在MongoDB中串联重复字符串值时忽略这些值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
推送
您的推荐答案示例使用$PUSH。$PUSH不隐藏重复项,而$addToSet则隐藏重复项。这是一个您可以考虑的代理...
(我擅自删除了空值,并使用逗号分隔结果。未指定值的排序顺序,因此它们被添加到无序条件中。)
聚合示例
db.collection.aggregate([
{
$match: { "comment": { $ne: null } }
},
{
$group:
{
_id: null,
comments: { $addToSet: "$comment" }
}
},
{
$addFields:
{
"comments":
{
$reduce:
{
input: "$comments",
initialValue: "",
in:
{
"$cond":
{
if:
{
"$eq":
[
{
"$indexOfArray": [ "$comments", "$$this" ]
},
0
]
},
then:
{
"$concat": [ "$$value", "$$this" ]
},
else:
{
"$concat": [ "$$value", ", ", "$$this" ]
}
}
}
}
}
}
}
])
结果
[
{
_id: null,
comments: 'waiting for pieces, waiting for approval, nothing'
}
]
这篇关于在MongoDB中串联重复字符串值时忽略这些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文