DOC: https://docs.mongodb.com/manu...html
{ _id: Objectd("123456789"), category: [ 'apple_1', 'apple_2', 'banana_1', 'banana_2' ] }
對test表的全部數據作category過濾,返回category中以apple開頭的元素mongodb
表原數據:數據庫
[ { _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表app
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) }) }
db.test.find({},{'category':{ '$elemMatch':{ $regex: 'apple' } }})
返回:dom
[ { _id: Objectd("id1"), category: [ 'apple_1', ] }, { _id: Objectd("id2"), category: [ 'apple_3', ] } ... ]
category只保留了符合過濾規則的第一個元素
db.test.aggregate( { $unwind: '$category' }, { $match: { category: { $regex: 'apple_' } } }, //unwind,match順序不能換 )
返回:code
[ { _id: Objectd("id1"), category: 'apple_1' }, { _id: Objectd("id1"), category: 'apple_2' }, { _id: Objectd("id2"), category: 'apple_3' }, { _id: Objectd("id2"), category: 'apple_4' } ... ]
將一個文檔拆分紅多個文檔返回
db.test.aggregate({ $project: { "category":{ $filter: { input: "$category", as: "cate", cond: { // category數組元素cate包含字符串'apple_' $eq: [ { $indexOfCP: ["$$cate", "apple_"] }, 0] } } } } })
返回:htm
[ { _id: Objectd("id1"), category: [ 'apple_1', 'apple_2' ] }, { _id: Objectd("id2"), category: [ 'apple_3', 'apple_4' ] } ... ]