gpt4 book ai didi

mongodb - 蒙戈 : Return specific fields from an array slice

转载 作者:可可西里 更新时间:2023-11-01 10:02:28 27 4
gpt4 key购买 nike

我想从 Mongo 中的数组返回特定​​字段,但遇到了问题。

假设我们有这样一个文档:

{
"student":"Bob",
"report_cards": [
{
"Year":2016,
"English":"B",
"Math":"A"
},
{
"Year":2015,
"English":"B",
"Math":"A"
}
]
}

我想返回以下内容:

{"Student": "Bob", {"English":"B"}}

基本上,我只需要报告卡数组中的第一个元素,并且只返回英文字段。

我知道它是周围的东西:

db.collection.find({},{"Student":1, "report_cards":{$slice:1}});

但这当然会返回完整数组(年、英语、数学)。我尝试了以下方法:

db.collection.find({},{"Student":1, "report_cards.$.english":{$slice:1}})
db.collection.find({},{"Student":1, "report_cards":{$slice:1, "$.english"}});

但这些都不正确。

如何简单地从数组结果中的 obj 返回一个字段?

谢谢!

最佳答案

您可以使用聚合框架来获取值作为

db.test.aggregate
([{$project:{_id:0,
student:'$student',
English:{ $arrayElemAt: ['$report_cards.English',0]
}}}])

关于mongodb - 蒙戈 : Return specific fields from an array slice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45489081/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com