簡體   English   中英

如何從數組中拉出元素,其中元素的字符串長度>較大?

[英]How to $pull elements from an array, $where elements' string length > a large number?

而舊的斜線轉義錯誤為我們留下了一些混亂的數據,如下所示:

{
    suggestions: [
        "ok",
        "not ok /////////// ... 10s of KBs of this ... //////",
    ]
}

我只想從數組中拉出那些不好的值。 我的第一個想法是基於匹配4個“ /”字符的正則表達式來$pull ,但是看起來正則表達式不適用於大字符串:

db.notes.count({suggestions: /\/\/\/\//}) // returns 0
db.notes.count({suggestions: {$regex: "////"}}) // returns 0

我的下一個想法是使用$where查詢查找suggestion字符串長於1000的文檔。該查詢有效:

db.notes.count({
    suggestions: {$exists: true},
    $where: function() {
        return !!this.suggestions.filter(function (item) {
            return (item || "").length > 1000;
        }).length
    }
})
// returns a plausible number

但是$where查詢不能用作$pull更新中的條件。

db.notes.update({
    suggestions: {$exists: true},
}, {
    $pull: {
        suggestions: {
            $where: function() {
                return !!this.suggestions.filter(function (item) {
                    return (item || "").length > 1000;
                }).length
            }
        }
    }
})

拋出

WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 81,
        "errmsg" : "no context for parsing $where"
    }
})

我的想法不多了。 我是否需要遍歷整個集合以及每個文檔的$set: {suggestions: suggestions.filter(...)} 沒有更好的方法從MongoDB的大型字符串數組中清除不良值?

(我只添加“ javascript”標簽即可獲得SO以正確設置代碼格式)

問題注釋中指出的簡單解決方案應該有效。 它確實適用於測試案例,可以重現原始問題。 正則表達式可以匹配大字符串,那里沒有特殊限制。

db.notes.updateOne({suggestions: /\/\//}, { "$pull": {suggestions: /\/\//}})

由於這對我不起作用,所以我最后討論了這個問題:通過基於字符串長度過濾數組元素來單獨更新所有文檔:

db.notes.find({
    suggestions: {$exists: true}
}).forEach(function(doc) {
    doc.suggestions = doc.suggestions.filter(function(item) {
        return (item || "").length <= 1000;
    }); db.notes.save(doc);
});

它運行緩慢,但是在這種情況下,這並不是真正的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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