我正在嘗試使用 MongoDB 聚合管道從一個集合中提取專案,檢查一個字串(一個 url),從中提取一個子字串,然后在第二個集合中檢查與第二個集合檔案之一的所述子字串匹配的檔案欄位。
收藏1檔案:
{
_id: ObjectId('xxxxxxxxxxxxxxxxxxx'),
url: 'https://example.com/WNE8UH'
}
編輯:productId 并不總是位于 url 字串的末尾。有時它就在中間,這迫使我在任何比較步驟之前提取它。
collection2 檔案:
{
_id: ObjectId('xxxxxxxxxxxxxxxxxxx'),
productId: 'WNE8UH'
}
看到url在 collection1 中包含WNE8UH哪些productId在 collection2 中?
如何使用聚合回傳 的子字串url,然后使用$lookup在 collection2productId欄位中定位檔案?
這是我當前的代碼:
db.collection1.aggregation([
{ $match: { url: RegExp( 'example.com', 'i' ) } },
{ $lookup: {
from: 'collection2',
let: {
productId: {
$regexFind: {
input: "$url",
regex: '(?<=com\/)\w{6}'
}
}
},
pipeline: [
{
$match: { productId: '$$productId'
}
}
],
as: 'matching_doc'
}}
])
結果
{
_id: ObjectId('xxxxxxxxxxxxxxxxxxx'),
url: 'https://example.com/WNE8UH',
matching_doc: []
}
獲取空陣列。我需要獲取匹配的檔案。
我究竟做錯了什么?
uj5u.com熱心網友回復:
詢問
- 查找是否在 URL 的末尾
url包含productId
*如果這個正則運算式不適合您的情況,您可以使用任何其他
*如果您想使用索引來匹配url您應該創建索引并使用正則運算式(^我^https://example.com/的意思是在查詢之前的查找)
玩蒙哥
coll1.aggregate(
[{"$lookup":
{"from": "coll2",
"let": {"url": "$url"},
"pipeline":
[{"$match":
{"$expr":
{"$regexMatch":
{"input": "$$url",
"regex": {"$concat": ["$productId", {"$literal": "$"}]}}}}}],
"as": "matching_doc"}}])
編輯
如果productId最后不是,但它總是在域名之后 example.com 你可以使用類似的東西
玩蒙哥
coll1.aggregate(
[{"$lookup":
{"from":"coll2",
"pipeline":
[{"$match":
{"$expr":
{"$regexMatch":
{"input":"$$url",
"regex":
{"$concat":["^https://example.com/", "$productId", "*"]}}}}}],
"as":"matching_doc",
"let":{"url":"$url"}}}])
如果它可以在 URL 內的任何位置,您可以使用如下所示的內容
coll1.aggregate(
[{"$lookup":
{"from": "coll2",
"pipeline":
[{"$match":
{"$expr":
{"$regexMatch": {"input": "$$url", "regex": "$productId"}}}}],
"as": "matching_doc",
"let": {"url": "$url"}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459376.html
