mongodb数组字段prefix匹配返回

DOC: https://docs.mongodb.com/manu...

collection(test)结构

{
    _id: Objectd("123456789"),
    category: [
        'apple_1',
        'apple_2',
        'banana_1',
        'banana_2'
    ]
}

Question:

对test表的所有数据做category过滤,返回category中以apple开头的元素

表原数据:

[    
    {
        _id: Objectd("id1"),
        category: [
            'apple_1',
            'apple_2',
            'banana_1',
            'banana_2'
        ]
    },
    {
        _id: Objectd("id2"),
        category: [
            'apple_3',
            'apple_4',
            'banana_1',
            'banana_2'
        ]
    }
    ...
]

返回数据示例:

[    
    {
        _id: Objectd("id1"),
        category: [
            'apple_1',
            'apple_2'
        ]
    },
    {
        _id: Objectd("id2"),
        category: [
            'apple_3',
            'apple_4'
        ]
    }
    ...
]

数据库try:随机构建test表

function getRandomArrayElements(arr, count) {
    var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}
var temp = ['apple_1','apple_2','banana_3','banana_4','pear_5','pear_6','pear_7'];
for(var i =0; i < 10; i ++){
    db.getCollection("test").insert({
            category:getRandomArrayElements(temp, Math.random()*7)
    })
}

Try 1:

db.test.find({},{'category':{
    '$elemMatch':{
        $regex: 'apple'
    }
}})

返回:

[    
    {
        _id: Objectd("id1"),
        category: [
            'apple_1',
        ]
    },
    {
        _id: Objectd("id2"),
        category: [
            'apple_3',
        ]
    }
    ...
]
category只保留了符合过滤规则的第一个元素

Try 2:

db.test.aggregate(
    {
        $unwind: '$category'
    },
    {
        $match: {
            category: {
             $regex: 'apple_'
            }
        }
    },
    //unwind,match顺序不能换
)

返回:

[    
    {
        _id: Objectd("id1"),
        category: 'apple_1'
    },
    {
        _id: Objectd("id1"),
        category: 'apple_2'
    },
    {
        _id: Objectd("id2"),
        category: 'apple_3'
    },
    {
        _id: Objectd("id2"),
        category: 'apple_4'
    }
    ...
]
将一个文档拆分成多个文档返回

Try 3(Solution):

db.test.aggregate({
    $project: {
        "category":{
            $filter: {
                input: "$category",
                as: "cate",
                cond: {
                    // category数组元素cate包含字符串'apple_'
                    $eq: [ {
                        $indexOfCP: ["$$cate", "apple_"]
                    }, 0] 
                }
            }
        }
    }
})

返回:

[    
    {
        _id: Objectd("id1"),
        category: [
            'apple_1',
            'apple_2'
        ]
    },
    {
        _id: Objectd("id2"),
        category: [
            'apple_3',
            'apple_4'
        ]
    }
    ...
]

相关推荐