我有兩個系列,一個是Users,另一個是Posts。我試圖find()在兩個集合中連接結果,但我在分頁時遇到了問題。我的問題是如何在一個查詢中實作這一點,以便我可以進行分頁。
例子:
Users:
{
_id: 1
username: 'test',
type: 'users'
...
}
帖子:
{
_id: 1,
name: 'test3',
type: 'posts',
...
}
當我搜索例如“test”時,我應該同時獲取用戶資料和用戶名/名稱中帶有“test”的發布資料。
另外,我嘗試了聚合,但在要連接的兩個表中沒有什么共同之處。我有一個問題,這些會導致許多搜索的性能問題嗎?
任何幫助表示贊賞。謝謝
uj5u.com熱心網友回復:
您可以使用$unionWith聚合階段。它執行兩個集合的并集。
$unionWith執行兩個集合的聯合。請注意,$unionWith從 MongoDB 4.2 版開始可用。$matchwith$regex僅過濾用戶名或名稱欄位包含指定字串的檔案。請注意,這$options: "i"將使搜索不區分大小寫。如果您想要區分大小寫的搜索,只需$options: "i"從查詢中洗掉。
db.users.aggregate([
{
"$unionWith": "posts"
},
{
"$match": {
"$or": [
{
"username": {
"$regex": "test",
"$options": "i"
}
},
{
"name": {
"$regex": "test",
"$options": "i"
}
}
]
}
}
])
作業示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357794.html
標籤:javascript 节点.js MongoDB 表达 猫鼬
上一篇:以后如何更改貓鼬模式的鍵?
