假设您有一个fileNames数组
[
'filename1_c4d.rar',
'text122_octane.c4d',
'texture1.png',
'texture2.png',
]在我的数据库中,我有一个Tags集合
[
{
_id: 'id1',
name: 'cinema4d',
aliases: ['.c4d', 'c4d', 'cinema4d'],
},
{
_id: 'id2',
name: 'octane',
aliases: ['octane'],
},
{
_id: 'id3',
name: 'textures',
aliases: ['texture', 'textures'],
},
// ...
]我的目标是在Tags的帮助下,在aliases中获取具有fileNames子字符串的所有mongoose。(Tags.find({ someFancyQuery: fileNames }))
下面是一个使它更容易理解的例子:
我有一个fileName:filename1_c4d.rar。基于这个名称,查询应该能够用名称filename1_c4d.rar来获取Tag,因为它的别名包含fileName cinema4d的一个子字符串
因此,这些fileNames应该获取以下Tags
filename1_c4d.rar➔cinema4dtext122_octane.c4d➔cinema4d, octanetexture1.png➔texturestexture2.png➔textures因此,最终查询的结果应该是那些Tags (没有重复):
cinema4d, octane, textures
P.S.:解释这是做什么的:
用户可以上传一个.rar文件,我希望根据文件名自动分配.rar文件中的标记。
我希望我的目标是清楚的。如果有什么你不明白的,请告诉我。
发布于 2018-12-21 22:48:55
您需要使用聚合管道来比较别名是输入数组的子字符串。
db.t5.aggregate([
{$addFields :{tags: tags, matches : {$map:{input: "$aliases", as: "a", in: {$map : {input: tags, as: "i", in: {$gte:[{$indexOfCP:["$$i", "$$a"]},0]}}}}}}},
{$addFields: {matchez :{$reduce : {input : "$matches", initialValue : [], in: { $concatArrays: [ "$$value", "$$this" ] }}}}},
{$match: {"matchez" : {$in : [true]}}},
{$group : {_id: null, names : {$addToSet : "$name"}}}
])结果
{ "_id" : null, "names" : [ "octane", "textures", "cinema4d" ] }样本收集
> db.t5.find()
{ "_id" : "id1", "name" : "cinema4d", "aliases" : [ ".c4d", "c4d", "cinema4d" ] }
{ "_id" : "id2", "name" : "octane", "aliases" : [ "octane" ] }
{ "_id" : "id3", "name" : "textures", "aliases" : [ "texture", "textures" ] }
{ "_id" : "id4" }
{ "_id" : "id5" }
{ "_id" : "id6" }输入标签
> tags
[
"filename1_c4d.rar",
"text122_octane.c4d",
"texture1.png",
"texture2.png"
]结果
> db.t5.aggregate([{$addFields :{tags: tags, matches : {$map:{input: "$aliases", as: "a", in: {$map : {input: tags, as: "i", in: {$gte:[{$indexOfCP:["$$i", "$$a"]},0]}}}}}}}, {$addFields: {matchez :{$reduce : {input : "$matches", initialValue : [], in: { $concatArrays: [ "$$value", "$$this" ] }}}}}, {$match: {"matchez" : {$in : [true]}}}, {$group : {_id: null, names : {$addToSet : "$name"}}}])
{ "_id" : null, "names" : [ "octane", "textures", "cinema4d" ] }
>https://stackoverflow.com/questions/53890895
复制相似问题