在mongodb中提取子数组值
这里是MongoDB noob 我有一个收藏如下在mongodb中提取子数组值,mongodb,mongo-shell,Mongodb,Mongo Shell,这里是MongoDB noob 我有一个收藏如下 > db.students.find({_id:22},{scores:[{type:'exam'}]}).pretty() { "_id" : 22, "scores" : [ { "type" : "exam", "score" : 75.04996547553947 },
> db.students.find({_id:22},{scores:[{type:'exam'}]}).pretty()
{
"_id" : 22,
"scores" : [
{
"type" : "exam",
"score" : 75.04996547553947
},
{
"type" : "quiz",
"score" : 10.23046475899236
},
{
"type" : "homework",
"score" : 96.72520512117761
},
{
"type" : "homework",
"score" : 6.488940333376703
}
]
}
如何通过mongo shell仅显示测验分数?您的原始示例中有一些语法可能没有达到预期效果。。也就是说,看起来您的意图是只匹配特定类型的分数(在您的示例中为“考试”,在您的描述中为“测验”) 下面是一些使用MongoDB 2.2 shell的示例
$elemMatch
投影
可以使用返回数组中的第一个匹配元素:
db.students.find(
// Search criteria
{ '_id': 22 },
// Projection
{ _id: 0, scores: { $elemMatch: { type: 'exam' } }}
)
结果将是每个文档的数组的匹配元素,例如:
{ "scores" : [ { "type" : "exam", "score" : 75.04996547553947 } ] }
聚合框架
如果要显示多个匹配值或重塑结果文档,而不是返回完整的匹配数组元素,可以使用:
这种情况下的结果包括:
{ "result" : [ { "score" : 75.04996547553947 } ], "ok" : 1 }
根据Stennie所说,他******建立了数据库。通过$elemMatch,如果我想要两个元素,类型:'考试'和类型:'测验'?plz可复制的
{ "result" : [ { "score" : 75.04996547553947 } ], "ok" : 1 }