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' ] } ... ]
相关推荐
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09
zhushenghan 2020-11-09
sunnnyduan 2020-10-16
不要皱眉 2020-10-14
xiaohai 2020-09-29
songxiugongwang 2020-09-22
萌亖 2020-09-17
LuckyLXG 2020-09-08
sdmzhu 2020-09-01
mkhhxxttxs 2020-09-16
xiaohai 2020-09-16
newcome 2020-09-09
jaylong 2020-08-19
大秦铁骑 2020-08-19
thatway 2020-08-19