我想從這 2 個集合中選擇具有主持人角色的用戶。
用戶集合
[
{
_id: "701",
username: "user1",
roles: [
"617",
"618"
]
},
{
_id: "702",
username: "user2",
roles: [
"617"
]
},
{
_id: "703",
username: "user3",
roles: [
"617",
"619"
]
},
{
_id: "704",
username: "user4",
roles: [
"617",
"619"
]
}
]
角色集合
[
{
_id: "617",
name: "simpleuser"
},
{
_id: "618",
name: "admin"
},
{
_id: "619",
name: "moderator"
}
]
在 SQL 中將是這樣的:
SELECT * FROM USERS
JOIN ROLES ON ROLE_ID = USER_ROLES
WHERE ROLE_NAME = "moderator"
我無法用 mongodb 貓鼬弄明白。請幫幫我。謝謝。
uj5u.com熱心網友回復:
您可以$lookup像這樣使用with 管道:
- 首先
$lookup匹配角色 id 使用,$in因為它在一個陣列中并$eq比較角色。 - 這將生成一個稱為
roles覆寫現有欄位的欄位(如果不想覆寫,可以更改名稱),然后用于$match匹配角色不為空的檔案(即與角色表有巧合)。
db.users.aggregate([
{
"$lookup": {
"from": "roles",
"let": {"roles": "$roles"},
"pipeline": [
{
"$match": {
"$expr": {
"$and": [
{"$in": ["$_id","$$roles"]},
{"$eq": ["$name","moderator"]}
]
}
}
}
],
"as": "roles"
}
},
{
"$match": {
"roles": {"$ne": [] }
}
}
])
示例在這里
使用貓鼬,您可以執行以下操作:
const result = await yourCollection.aggregate(/*the query*/)
res.status(200).send(result) // or whatever
或者使用回呼
yourCollection.aggregate(/*the query*/).then(result => {res.status(200).send(result)})
此外,您可以使用$projectstage 將您想要的欄位發送到前端,例如,僅發送username您可以使用此查詢
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355641.html
標籤:MongoDB 猫鼬 mongodb-查询
