我在MongoDB中的文档结构如下:
{ _id : 1, tokens : [ "one","two","three","four","five","six","seven" ] }
{ _id : 2, tokens : [ "two","three","four","one","one","five","eight" ] }
{ _id : 3, tokens : [ "six","three","four","five","one","five","nine" ] }
平均而言,文档包含长度为4500项的令牌数组。
我需要进行某种模式匹配,其中我有完全匹配的令牌数组,即假设我必须在完全匹配的顺序中找到以下内容...
["three","four","five"]
...我希望我的查询能够提供以下文件......
{ _id : 1, tokens : [ "one","two","three","four","five","six","seven" ] }
{ _id : 3, tokens : [ "six","three","four","five","one","five","nine" ] }
即。这两个文档都包含我在数组中搜索的项目的确切顺序。
我搜索的数组可能有不同的长度,范围从1到15个令牌。
我正在寻找以下内容:
感谢您的帮助。
答案 0 :(得分:0)
它会很慢,但你可以使用$where
运算符执行此操作;将其与$all
运算符配对以帮助提高性能。
db.test.find({
tokens: {$all: ["three","four","five"]},
$where: function() {
var ix = -1;
// Find each occurrence of 'three' in this doc's tokens array and return
// true if it's followed by 'four' and 'five'.
do {
ix = this.tokens.indexOf('three', ix + 1);
if (ix !== -1 && ix+2 < this.tokens.length &&
this.tokens[ix+1] === 'four' && this.tokens[ix+2] === 'five') {
return true;
}
} while (ix !== -1);
return false;
}
})