[英]How to create model with an array field which contains another documents as an embedded documents in Mongodb (Mongoid)
[英]Return documents of which field of type array contains array in exact order
我在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個標記。
我正在尋找以下內容:
謝謝你的幫助。
這會很慢,但是您可以使用$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;
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.