我想使用 MongoDB 聚合來獲取集合Events中的一些檔案,這些檔案參考Program具有約束的集合Program.type
活動
{
_id: ObjectId,
programId: ObjectId
}
程式
{
_id: ObjectId,
type: "Type A"
}
類似 sql 的偽查詢就像select * from events where event.id = 1234 and where program.type = "Type A"
我有這個,我不知道我在做什么。
const pipeline = [
{
$match: {_id: id}
},
{
$lookup: {
from: 'programs',
localField: '_id',
foreignField: 'programId',
as: 'program'
}
},
{
$unwind: '$program'
},
{
$match: {'program.type': 'Type A'}
}
]
我實際上認為這有效,但是當我嘗試不同的型別時它失敗了。
uj5u.com熱心網友回復:
如果我沒記錯的話,這個查詢:
select * from events where event.id = 1234 and where program.type = "Type A"
這個查詢是:
db.events.aggregate([
{
"$match": {
"_id": 1
}
},
{
"$lookup": {
"from": "programs",
"as": "programs",
"pipeline": [
{
"$match": {
"$expr": {
"$eq": [
"$type",
"A"
]
}
}
}
]
}
}
])
在哪里:
- select * -> 是在 mongo db 中默認獲取所有欄位
- 來自事件->
db.events.aggregate - 其中 event.id = 1234 -> 是
$match - program.type = "Type A" ->
$lookupwith pipeline where{"$eq": ["$type","A"]}
這里的例子
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422849.html
標籤:
