[英]Query for documents where match contiguous array elements
我有一個 MongoDB 集合,其中包含以下格式的文檔:
{ "_id" : 1, "tokens": [ "I", "have", "a", "dream" ] },
{ "_id" : 2, "tokens": [ "dream", "a", "little", "dream" ] },
{ "_id" : 3, "tokens": [ "dream", "a", "dream" ] },
{ "_id" : 4, "tokens": [ "a" , "little", "dream" ] },
...
我需要獲取所有“令牌”包含連續數組元素的文件: “a”、“dream” 。 因此,以下是匹配的文件:
{ "_id" : 1, "tokens": [ "I", "have", "a", "dream" ] },
{ "_id" : 3, "tokens": [ "dream", "a", "dream" ] },
有沒有辦法得到正確的結果?
一個技巧就是有一個正則表達式。
$match
獲取具有$all
數組輸入的所有文檔$addFields
具有重復的標記和輸入數組$reduce
有助於連接所有字符串連接-
$regexMatch
匹配兩個字符串$match
消除不需要的數據$project
僅獲取必要的字段代碼是
[{
$match: {
tokens: { $all: ["a", "dream"] }
}
}, {
$addFields: {
duplicate: "$tokens",
inputData: ["a", "dream"]
}
}, {
$addFields: {
duplicate: {
$reduce: {
input: "$duplicate",
initialValue: "",
in: { $concat: ["$$value", "-", "$$this"] }
}
},
inputData: {
$reduce: {
input: "$inputData",
initialValue: "",
in: { $concat: ["$$value", "-", "$$this"] }
}
}
}
}, {
$addFields: {
match: {
$regexMatch: { input: "$duplicate", regex: '$inputData' }
}
}
}, {
$match: {
match: true
}
}, {
$project: { _id: 1, tokens: 1 }
}]
工作蒙戈游樂場
注意:請檢查多個場景,盡管它適用於這種場景
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.