Mongo DB聚合查询匹配和项目以及运算符不工作

时间:2016-09-30 04:29:11

标签: mongodb

我在mongo db中有这个文件:

 {
        "_id" : 8,
        "semester" : 3,
        "grades" : [ 
            {
                "grade" : 92,
                "mean" : 88,
                "std" : 8,
                "scores" : [ 
                    {
                        "fistSem" : 100,
                        "secondSem" : 60
                    }
                ]
            }, 
            {
                "grade" : 78,
                "mean" : 90,
                "std" : 5,
                "scores" : [ 
                    {
                        "fistSem" : 100,
                        "secondSem" : 60
                    }
                ]
            }, 
            {
                "grade" : 88,
                "mean" : 85,
                "std" : 3,
                "scores" : [ 
                    {
                        "fistSem" : 72,
                        "secondSem" : 60
                    }
                ]
            }
        ]
    }

此查询

db.getCollection('grades').aggregate({"$project":{"grades.std":1,"grades.grade":1}},{"$match":{"$and":[{"grades.grade":92},{"grades.std":8}]}});

给我以下输出:

{
    "_id" : 8,
    "grades" : [ 
        {
            "grade" : 92,
            "std" : 8
        }, 
        {
            "grade" : 78,
            "std" : 5
        }, 
        {
            "grade" : 88,
            "std" : 3
        }
    ] }

我期待:

{
    "_id" : 8,
    "grades" : [ 
        {
            "grade" : 92,
            "std" : 8
        } ] }

不确定我们为什么会得到非匹配的数组元素。我们正在使用mongo db 3.2

2 个答案:

答案 0 :(得分:2)

尝试以下查询:

db.getCollection('grades').find({"grades.grade":92"grades.std":8},{"grades.$":1});

<强>更新

db.getCollection('grades').aggregate([
{$match:{_id:8}},
{$unwind:"$grades"},
{$match:{"grades.grade":92,"grades.std":8}},
{$project:{"_id":"$_id",grades:{grade:"$grades.grade", std:"$grades.std"}}}
]);

答案 1 :(得分:0)

试试这个

db.getCollection('grades').find({"grades.grade":92, "grades.std":8},{"grades.$":1})

输出

{
    "_id" : 8,
    "grades" : [ 
        {
            "grade" : 92,
            "mean" : 88,
            "std" : 8,
            "scores" : [ 
                {
                    "fistSem" : 100,
                    "secondSem" : 60
                }
            ]
        }
    ]
}