共计 1668 个字符,预计需要花费 5 分钟才能阅读完成。
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’
]
}
…
]