我有這個 mongo DB 查詢,它查詢一個名為的集合songs,并為每首歌曲回傳相關的相應專輯:
db.songs.aggregate([{
$lookup: {
from: "albums",
let: { album: '$album' },
as: "album",
pipeline: [{
$match: {
$expr: {
$and: [
{ $eq: ['$albumId', '$$album._id'] },
{ $eq: ['$status', 'Draft'] },
]
}
}
}]
}
}])
在上面的查詢中,我的意圖是僅在專輯處于狀態時才回傳一首歌曲Draft,但相反,它回傳所有歌曲,對于專輯不在 Draft 中的歌曲,它只回傳一個空陣列抬頭。如果專輯不在草稿中,我怎么能完全不回傳歌曲檔案?
此外,是否可以展平檔案中的結果?即,將專輯的所有欄位合并到歌曲檔案中?
uj5u.com熱心網友回復:
執行后,$lookup您可以使用空陣列過濾掉檔案:
{ $match: { album: { $ne: [] } }}
然后在 MongoDB 檔案中有一個與您的案例非常相似的操作$mergeObjects員示例。假設每首歌曲屬于一張專輯,將聚合管道放在一起可能如下所示:
db.songs.aggregate([
{
$lookup: {
from: "albums",
let: { album: '$album' },
as: "album",
pipeline: [{
$match: {
$expr: {
$and: [
{ $eq: ['$albumId', '$$album._id'] },
{ $eq: ['$status', 'Draft'] },
]
}
}
}]
}
},
{ $match: { album: { $ne: [] } }},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$album", 0 ] }, "$$ROOT" ] } }
},
{ $project: { album: 0 } }
])
uj5u.com熱心網友回復:
您可能想嘗試另一個方向:在其中查找專輯status = Draft然后獲取歌曲:
db.album.aggregate([
{$match: {"status":"Draft"}}
,{$lookup: {from: "song",
localField: "album", foreignField: "album",
as: "songs"}}
// songs is now an array of docs. Run $map to turn that into an
// array of just the song title, and overwrite it (think x = x 1):
,{$addFields: {songs: {$map: {
input: "$songs",
in: "$$this.song"
}} }}
]);
如果您在檔案中有很多材料song,您可以使用 fancier$lookup來減少查找陣列中檔案的大小——但您仍然需要$map將其轉換為字串陣列。
db.album.aggregate([
{$match: {"status":"Draft"}}
,{$lookup: {from: "song",
let: { aid: "$album" },
pipeline: [
{$match: {$expr: {$eq:["$album","$$aid"]}}},
{$project: {song:true}}
],
as: "songs"}}
,{$addFields: {songs: {$map: {
input: "$songs",
in: "$$this.song"
}} }}
]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/412263.html
標籤:
下一篇:Neo4j查詢未回傳所需的輸出
