我想從一個嵌套陣列中的特定物件中選擇一些特定的欄位,通過mongoose/mongo實作。
考慮到資料:
[
{
"_id"。ObjectId("5ff4b728b6af610f0851d2a6") 。
"totalScore"。500。
"totalCompleted": 100,
"monthly": [
{
年。2021,
月。8,
嘗試過: 10,
完成了。5,
score: 20,
}
],
},
我想首先得到所有的檔案,然后在 "月 "里面,我想只選擇與月=8相匹配的檔案,并且只回傳 "分數 "欄位,而忽略其余的欄位,如 "嘗試"、"完成 "等等。
到目前為止,我已經嘗試了以下的查詢:
db.collection.find({},
{
totalScore: 1,
"月刊": {
$elemMatch: {
年。2021,
月。8,
},
},
})
它回傳整個 "月 "物件的所有鍵。像這樣:
[
{
"_id"。ObjectId("5ff4b728b6af610f0851d2a6") 。
"monthly": [
{
"試圖"。10,
"完成": 5,
"月": 8,
" score": 20,
"年份": 2021"totalScore": 500
},
]
但是,我想要的是,只選擇 "月度 "中的 "分數 "欄位。 因此,結果資料將是:
[
{
"_id"。ObjectId("5ff4b728b6af610f0851d2a6") 。
"monthly": [
{
" score": 20,
}
],
"totalScore": 500。
},
我應該如何處理這個問題?
uj5u.com熱心網友回復:
這可以通過使用$map和$filter的簡單聚合來完成:
db.collection.aggregate( [
{
$project: {
totalScore: 1,
monthly: {
$map: {
input: {
$filter: {
input: "$monthly"。
as: "item",
cond: {
$eq: [
"$$item.month",
8.
]
}
}
},
as: "item",
in: {
score: "$item.score"。
}
}
}
}
}
])
在mongoplayground上的例子。https://mongoplayground.net/p/5PbR49Ufxb5
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/307934.html
標籤:
