我有兩個集合,即:clib和mp. 的架構clib是 :{name: String, type: Number}和架構mp是:{clibId: String}。
示例檔案clib:
{_id: ObjectId("6178008397be0747443a2a92"), name: "c1", type: 1}
{_id: ObjectId("6178008397be0747443a2a91"), name: "c2", type: 0}
示例檔案mp:
{clibId: "6178008397be0747443a2a92"}
{clibId:"6178008397be0747443a2a91"}
在查詢時mp,我希望那些clibId's有type = 0在clib集合。
任何想法如何實作?
我能想到的一種方法是使用$lookUp,但這似乎不起作用。另外,我也不太清楚,如果這是MongoDB的反模式,另一種方法是復制type自clib到mp,同時節省mp document。
uj5u.com熱心網友回復:
如果我理解正確,您可以使用這樣的管道:
此查詢從clib它_id的相同位置獲取值,clibId并且還具有type = 0. 此外,我還添加了一個$match階段,在沒有任何巧合的情況下不輸出值。
db.mp.aggregate([
{
"$lookup": {
"from": "clib",
"let": {
"id": "$clibId"
},
"pipeline": [
{
"$match": {
"$expr": {
"$and": [
{
"$eq": [
{
"$toObjectId": "$$id"
},
"$_id"
]
},
{
"$eq": [
"$type",
0
]
}
]
}
}
}
],
"as": "result"
}
},
{
"$match": {
"result": {
"$ne": []
}
}
}
])
示例在這里
uj5u.com熱心網友回復:
db.mp.aggregate([
{
$lookup: {
from: "clib",
let: {
clibId: "$clibId"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [ "$_id", "$$clibId" ],
}
]
}
}
},
{
$project: { type: 1, _id: 0 }
}
],
as: "clib"
}
},
{
"$unwind": "$clib"
},
{
"$match": {
"clib.type": 0
}
}
])
在這里測驗
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/338403.html
