【问题标题】:Mongoose Find All Documents Matching a Substring of InputsMongoose 查找与输入子串匹配的所有文档
【发布时间】:2018-12-21 21:20:23
【问题描述】:

假设你有这个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'],
    },
    // ...
]

我的目标是在mongoose 的帮助下获取所有Tagsaliases 中具有我的fileNames 子字符串的Tags。 (Tags.find({ someFancyQuery: fileNames }))


下面是一个例子,以便更好地理解:

我有这个文件名:filename1_c4d.rar。基于此名称,查询应该能够获取名称为 cinema4dTag,因为它的别名包括文件名的子字符串 filename1_c4d.rar

所以这些文件名应该获取以下Tags

  • filename1_c4d.rarcinema4d

  • text122_octane.c4dcinema4d, octane

  • texture1.pngtextures

  • texture2.pngtextures


所以最终查询的结果应该是那些Tags(不重复):

cinema4d, octane, textures


P.S.:解释一下这是为了什么:

用户可以上传例如.rar 文件,我想根据 .rar 文件中的文件名自动分配标签。


我希望我的目标很明确。如果有什么不懂的地方请告诉我。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query tagging


    【解决方案1】:

    您需要使用聚合管道来比较别名是输入数组的子字符串

    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" ] }
    >
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2017-08-21
      • 2019-05-06
      • 2014-03-21
      • 2018-08-11
      • 2016-04-23
      • 2020-02-19
      • 2017-07-20
      • 2017-05-13
      相关资源
      最近更新 更多