MongoDB query $in with regex array of element

前端 未结 5 1440
野趣味
野趣味 2020-12-16 18:09

Ok i am trying to implement a query, which is trying to perform regex search ( which contains an array list ) on a bunch of document

Its hard for me to explain...so

5条回答
  •  醉梦人生
    2020-12-16 19:00

    Using $in can be fairly efficient with small arrays but not so well with huge lists since it will skip around in the index to find the matching documents, or walk through the whole collection if there isn't an index to use.

    Besides using the $in with the regular expression, you could use a pipe-delimited regex pattern with the keywords list like this:

    Test documents:

    db.papertest.insert([
        { category: "ad bd cd" },
        { category: "dd ed fd" },
        { category: "gd hd id" },
        { category: "jd kd ld" },
        { category: "md nd od" },
        { category: "pd qd rd" },
        { category: "sd td ud" },
        { category: "vd wd xd yd zd" },
    ]);
    

    The magic:

    var keywords = ["xd", "sd", "ad"],
        regex = keywords.join("|");
    
    db.papertest.find({
        "category": {
            "$regex": regex, 
            "$options": "i"
        } 
    });
    

    The results

    { "_id" : ObjectId("56bb6f171bb4f693057c0ba4"), "category" : "ad bd cd" }
    { "_id" : ObjectId("56bb6f171bb4f693057c0baa"), "category" : "sd td ud" }
    { "_id" : ObjectId("56bb6f171bb4f693057c0bab"), "category" : "vd wd xd yd zd" }
    

提交回复
热议问题