我有一個這樣的聚合:
const files = await File.aggregate([
{
$match: { facilityId: { $in: facilities } }
},
{
$sort: { createdAt: 1 }
},
{
$project: {
file: 0,
}
}
])
而且我希望每個“設施”只回傳 4 個檔案,我曾經做過類似facilities.map(id => query(id))但 id 喜歡在生產環境中加快速度的事情。
使用 $limit 將限制整個查詢,這不是我想要的,我嘗試在投影階段使用 $slice 但出現錯誤:
MongoError: Bad projection specification, cannot include fields or add computed fields during an exclusion projection
我怎樣才能在單個查詢中實作這一點?
集合的架構是:
const FileStorageSchema = new Schema({
name: { type: String, required: true },
userId: { type: String },
facilityId: { type: String },
patientId: { type: String },
type: { type: String },
accessed: { type: Boolean, default: false, required: true },
file: {
type: String, //
required: true,
set: AES.encrypt,
get: AES.decrypt
},
sent: { type: Boolean, default: false, required: true },
},
{
timestamps: true,
toObject: { getters: true },
toJSON: { getters: true }
})
我想回傳除file包含編碼為 base64 的加密 blob 的欄位之外的所有欄位。
另外:我覺得我的方法不正確,我真正想要的是能夠一次查詢所有設施 ID,但僅限于為每個設施創建的 4 個最新檔案,我雖然使用聚合可以幫助我實作這但我開始認為它不是如何完成的。
uj5u.com熱心網友回復:
從問題來看,模式尚不清楚。所以我有兩個基于兩個模式的答案。請使用適合您的方法
#1
db.collection.aggregate([
{
$match: {
facilityId: {
$in: [
1,
2
]
}
}
},
{
$group: {
_id: "$facilityId",
files: {
$push: "$file"
}
}
},
{
$project: {
files: {
$slice: [
"$files",
0,
4
],
}
}
}
])
在這里測驗
#2
db.collection.aggregate([
{
$match: {
facilityId: {
$in: [
1,
2
]
}
}
},
{
$project: {
facilityId: 1,
file: {
$slice: [
"$file",
4
]
}
}
}
])
在這里測驗
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/339587.html
上一篇:基于陣列中的值查找
