通过$ elemMatch在mongodb中提取两个子数组值 [英] Extract two sub array values in mongodb by $elemMatch

查看:439
本文介绍了通过$ elemMatch在mongodb中提取两个子数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

聚集,$ unwind和$ group并不是我的解决方案,因为它们使查询非常慢,因为我希望通过db.collection.find()方法获取记录.

Aggregate, $unwind and $group is not my solution as they make query very slow, there for I am looking to get my record by db.collection.find() method.

问题是我需要从子数组中获取多个值.例如,从下面的示例中,我想获取"type":"exam" "type":"quiz" 元素.

The problem is that I need more then one value from sub array. For example from the following example I want to get the "type" : "exam" and "type" : "quiz" elements.

{
    "_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" } ] }  

但是,这会导致类型:考试" ,并且仅返回类型:测验" .有谁知道如何使用 db.find()做到这一点?

But this over ride the type: 'exam' and returns only type: 'quiz'. Have anybody any idea how to do this with db.find()?

推荐答案

由于以下对elemMatchmongo array fields的限制,因此无法直接使用findelemMatch来实现.

This is not possible directly using find and elemMatch because of following limitation of elemMatch and mongo array fields.

$ elemMatch运算符将查询结果中字段的内容限制为仅包含与$ elemMatch条件匹配的第一个元素.参考来自 $ elemMacth

和mongo数组字段限制如下所示

and mongo array field limitations as below

投影文档中只能出现一个位置$运算符.

Only one positional $ operator may appear in the projection document.

查询文档只应在要投影的数组字段上包含一个条件.多个条件可能在内部相互覆盖并导致不确定的行为.从 mongo数组字段限制

The query document should only contain a single condition on the array field being projected. Multiple conditions may override each other internally and lead to undefined behavior. ref from mongo array field limitations

因此,您尝试按照此方法仅查找examquiz

So either you tried following this to find out only exam or quiz

db.collectionName.find({"_id":22,"scores":{"$elemMatch":{"type":"exam"}}},{"scores.$.type":1}).pretty()

仅显示exam分数数组.

否则,您应该通过aggregation

这篇关于通过$ elemMatch在mongodb中提取两个子数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆