// Schema:
const UserSchema = mongoose.Schema({
name: { type: String },
motos: [
{
model: { type: String }
},
],
});
// Motos enabled:
motosEnabled = [
{
model: 'A1',
},
{
model: 'A2',
},
];
User.insertMany([
{ name: 'Kartik', motos: [{ model: 'A1' }, { model: 'A3' }] },
{ name: 'Niharika', motos: [{ model: 'A1' }, { model: 'A2' }] },
])
我想撰寫一個查詢,該查詢將回傳所有用戶,但僅過濾前一個陣列啟用的 motos。我正在嘗試使用聚合,但我做不到。謝謝你的幫助 !
預期輸出:
[
{ name: 'Kartik', motos: [{ model: 'A1' }] },
{ name: 'Niharika', motos: [{ model: 'A1' }, { model: 'A2' }] }
]
uj5u.com熱心網友回復:
詢問
- 您可以使用
$filter - 而不是
[{"model": "A1"}, {"model": "A2"}]把 js 變數motosEnabled - filter 檢查 array(
motosEnabled) 是否包含檔案{"model" ".."}并且它通過與否
測驗代碼在這里
aggregate(
[{"$set":
{"motos":
{"$filter":
{"input": "$motos",
"cond":
{"$in":
[{"model": "$$this.model"}, [{"model": "A1"}, {"model": "A2"}]]}}}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/368043.html
