【发布时间】:2021-09-16 22:20:50
【问题描述】:
我想从嵌套数组中的特定对象中选择一些特定字段,通过 mongoose/mongo 实现。
考虑数据:
[
{
"_id": ObjectId("5ff4b728b6af610f0851d2a6"),
"totalScore": 500,
"totalCompleted": 100,
"monthly": [
{
year: 2021,
month: 8,
attempted: 10,
completed: 5,
score: 20,
}
],
},
]
我想首先获取所有文档,然后在“每月”中,我只想选择匹配月份 = 8 的文档,只返回“分数”字段并忽略“尝试”等其他字段"、"完成"等
到目前为止,我已经尝试过以下查询:
db.collection.find({},
{
totalScore: 1,
"monthly": {
$elemMatch: {
year: 2021,
month: 8,
},
},
})
它返回整个“月”对象的所有键。像这样:
[
{
"_id": ObjectId("5ff4b728b6af610f0851d2a6"),
"monthly": [
{
"attempted": 10,
"completed": 5,
"month": 8,
"score": 20,
"year": 2021
}
],
"totalScore": 500
},
]
但是,我想要的是只从“每月”中选择“分数”字段。 所以结果数据是:
[
{
"_id": ObjectId("5ff4b728b6af610f0851d2a6"),
"monthly": [
{
"score": 20,
}
],
"totalScore": 500
},
我应该如何解决这个问题?
【问题讨论】:
标签: mongodb mongoose mongodb-query