【发布时间】:2015-06-22 16:49:46
【问题描述】:
Aggregate、$unwind 和 $group 不是我的解决方案,因为它们使查询非常慢,我希望通过 db.collection.find() 方法获取我的记录。
问题是我需要子数组中的多个值。例如,从以下示例中,我想获取 "type" : "exam" 和 "type" : "quiz" 元素。
{
"_id" : 22,
"scores" : [
{
"type" : "exam",
"score" : 75.04996547553947
},
{
"type" : "quiz",
"score" : 10.23046475899236
},
{
"type" : "homework",
"score" : 96.72520512117761
},
{
"type" : "homework",
"score" : 6.488940333376703
}
]
}
我看起来像
db.students.find(
// Search criteria
{ '_id': 22 },
// Projection
{ _id: 1, scores: { $elemMatch: { type: 'exam', type: 'quiz' } }}
)
结果应该是这样的
{ "_id": 22, "scores" : [ { "type" : "exam", "type" : "quiz" } ] }
但这会覆盖 type: 'exam' 并且只返回 type: 'quiz'。有人知道如何使用 db.find() 做到这一点吗?
【问题讨论】: