具有多个ID的MongoDB组 [英] MongoDB group with multiple id

查看:354
本文介绍了具有多个ID的MongoDB组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组文档,每个文档中都有20多个键,并且键随文档的不同而不同.某些键可能并非在所有文档中都存在.我正在尝试使用聚合框架运行MongoDB组操作.查询看起来像这样-

I have a set of documents with more than 20 keys in each of them, and the keys vary with documents. Some keys may not be present in all the documents. I am trying to run a MongoDB group operation using the aggregation framework. The query looks something like this -

db.collection.aggregate([{'$group': {'count': {'$sum': 1}, '_id': {'location': '$location', 'type': '$type', 'language': '$language'}}}])

在理想情况下,它应该返回应该存在3个键的文档,并对它们执行分组"操作.但是结果看起来像这样-

In ideal case, it should return the documents where 3 of the keys should be present and perform a "group-by" operation on them. But the result looks something like this -

{
    "result" : [
        {
            "_id" : {
                "location" : "abc",
                "type" : "456"
            },
            "count" : 5
        },
        {
            "_id" : {
                "type" : "123",
                "language" : "english"
            },
            "count" : 1
        },
        {
            "_id" : {
                "location" : "ghi",
                "type" : "9876",
                "language" : "latin"
            },
            "count" : 2
        },
        {
            "_id" : {
                "language" : "hebrew",
                "type" : "9434"
            },
            "count" : 3
        },
        {
            "_id" : {
                "type" : "525",
                "location" : "cari"
            },
            "count" : 1
        },
        {
            "_id" : {
                "language" : "spanish",
                "location" : "dff"
            },
            "count" : 12
        },
        {
            "_id" : {
                "location" : "adpj",
                "type" : "3463",
                            "language": "english"
            },
            "count" : 8
        },
        {
            "_id" : {
                "language" : "french",
                "location" : "nts"
            },
            "count" : 6
        }
    ],
    "ok" : 1
}

问题是,即使MongoDB找不到我在查询中要求的所有3个键并显示部分group by,它也会执行组操作.我只对获得所有密钥的结果感兴趣.不能在客户端进行过滤.有人可以帮忙吗?

The problem is, MongoDB does the group operation even when it does not find all 3 keys I asked for in the query and shows partial group by. I am only interested in the results where I get all the keys. Filtering in the client side is not an option. Can anyone help out?

推荐答案

查询:

db.collection.aggregate([{
    $match: {
        type: {
            "$exists": true
        },
        location: {
            "$exists": true
        },
        language: {
            "$exists": true
        }
    }
}])

这篇关于具有多个ID的MongoDB组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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