簡體   English   中英

返回數組類型字段包含確切順序的數組的文檔

[英]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個標記。

我正在尋找以下內容:

  • 這對MongoDB查詢可行嗎? 我已經閱讀,並重新閱讀並重新閱讀了很好的文檔,但是找不到解決方案,例如使用$ all。
  • 也許有更好的方法來存儲這樣的令牌來完成我需要的工作嗎?

謝謝你的幫助。

這會很慢,但是您可以使用$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM