[英]Query for documents where match contiguous array elements
I have a MongoDB collection with documents in the following format:我有一个 MongoDB 集合,其中包含以下格式的文档:
{ "_id" : 1, "tokens": [ "I", "have", "a", "dream" ] },
{ "_id" : 2, "tokens": [ "dream", "a", "little", "dream" ] },
{ "_id" : 3, "tokens": [ "dream", "a", "dream" ] },
{ "_id" : 4, "tokens": [ "a" , "little", "dream" ] },
...
I need to get all doucuments which "tokens" include contiguous array elements: "a", "dream" .我需要获取所有“令牌”包含连续数组元素的文件: “a”、“dream” 。 So, the following are matched doucuments:
因此,以下是匹配的文件:
{ "_id" : 1, "tokens": [ "I", "have", "a", "dream" ] },
{ "_id" : 3, "tokens": [ "dream", "a", "dream" ] },
Is there a way to get the right results?有没有办法得到正确的结果?
A trick that is to have a regexp.一个技巧就是有一个正则表达式。
$match
to get the all documents which has $all
array input $match
获取具有$all
数组输入的所有文档$addFields
to have a duplicate the tokens and input array $addFields
具有重复的标记和输入数组$reduce
helps to concat all string joining -
$reduce
有助于连接所有字符串连接-
$regexMatch
to match both strings $regexMatch
匹配两个字符串$match
to eliminate unwanted data $match
消除不需要的数据$project
to get necessary fields only $project
仅获取必要的字段The code is代码是
[{
$match: {
tokens: { $all: ["a", "dream"] }
}
}, {
$addFields: {
duplicate: "$tokens",
inputData: ["a", "dream"]
}
}, {
$addFields: {
duplicate: {
$reduce: {
input: "$duplicate",
initialValue: "",
in: { $concat: ["$$value", "-", "$$this"] }
}
},
inputData: {
$reduce: {
input: "$inputData",
initialValue: "",
in: { $concat: ["$$value", "-", "$$this"] }
}
}
}
}, {
$addFields: {
match: {
$regexMatch: { input: "$duplicate", regex: '$inputData' }
}
}
}, {
$match: {
match: true
}
}, {
$project: { _id: 1, tokens: 1 }
}]
Working Mongo playground工作蒙戈游乐场
Note: Do check multiple scenarios although its working for this scenario注意:请检查多个场景,尽管它适用于这种场景
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.