作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我想从 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/
我是一名优秀的程序员,十分优秀!