[英]Return documents of which field of type array contains array in exact order
I'm having documents in MongoDB structured like this: 我在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" ] }
On average the documents contain token arrays with a length of 4500 items. 平均而言,文档包含长度为4500项的令牌数组。
I need to do some sort of pattern matching, where I have arrays of tokens in exact order to match, ie let's say I have to find the following in exactly matching order... 我需要进行某种模式匹配,其中我要按完全相同的顺序排列令牌数组,也就是说,我必须按完全匹配的顺序查找以下内容...
["three","four","five"]
...I want my query to provide me the following documents... ...我希望我的查询向我提供以下文件...
{ _id : 1, tokens : [ "one","two","three","four","five","six","seven" ] }
{ _id : 3, tokens : [ "six","three","four","five","one","five","nine" ] }
Ie both documents contain the exact order of the items I had in my array to search with. 也就是说,两个文档都包含我要在数组中搜索的项目的确切顺序。
Arrays I search with may have different lengths, ranging from 1 to 15 tokens. 我搜索的数组可能具有不同的长度,范围从1到15个标记。
I'm looking for the following: 我正在寻找以下内容:
Thanks for any help. 谢谢你的帮助。
It's going to be slow, but you can do this with a $where
operator; 这会很慢,但是您可以使用$where
运算符来完成; pairing it with an $all
operator to help with performance. 将其与$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;
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.