mongodb选择所有不为null或为空字符串的字段

时间:2019-12-30 13:13:09

标签: mongodb mongodb-query aggregation-framework

我有mongodb文档,其数据如下:

{
  "_id": "ObjectId(\"5e09db41d4ccee7f500f7326\")",
  "time": "ISODate(\"2019-12-30T09:10:53Z\")",
  "syslog_fac": 23,
  "syslog_sever": 6,
  "syslog_tag": "",
  "procid": "",
  "pid": "-",
  "status": "Allowed",
  "logtype": "Firewall Logs",
  "date": "2019-12-30",
  "Module": "01UM",
  "Desc": "Theuserloggedout.(UserName",
  "Severity_Level": "6",
  "Vsys": "public",
  "SourceIP": "10.10.0.57",
  "ParentGroup": "/netgrup.com.tr",
  "LogonTime": "2019/12/3014:07:20",
  "LogoutTime": "2019/12/3014:10:53",
  "ObversePackets": "0",
  "ObverseBytes": "0",
  "ReversePackets": "0",
  "ReverseBytes": "0",
  "LogoutReason": "AnIPaddressconflictoccurred",
  "VSys": "",
  "PolicyName": "",
  "Country": "",
  "DestinationIP": "",
  "SourcePort": "",
  "DestinationPort": "",
  "SourceZone": "",
  "DestinationZone": "",
  "User": "",
  "Protocol": "",
  "ApplicationName": "",
  "Profile": "",
  "Type": "",
  "Category": "",
  "SubCategory": "",
  "Page": "",
  "Host": "",
  "Referer": "",
  "Item": "",
  "Action": "",
  "level": "",
  "SourceNatIP": "",
  "SourceNatPort": "",
  "BeginTime": "",
  "EndTime": "",
  "SendPkts": 0,
  "SendBytes": 0,
  "RcvPkts": 0,
  "RcvBytes": 0,
  "SourceVpnID": "",
  "DestinationVpnID": "",
  "CloseReason": "",
  "Task": "",
  "Ip": "",
  "VpnName": "",
  "AuthenticationMethod": "",
  "Command": "",
  "user-name": "",
  "attack-type": "",
  "interface": "",
  "packet-count": "",
  "rate-number": "",
  "file-name": "",
  "file-type": "",
  "direction": "",
  "detect-type": "",
  "virus-name": "",
  "signature-id": "",
  "event-number": "",
  "target": "",
  "role": "",
  "user": ""
}

如您所见,有很多字段具有空字符串或0,所以我想做的是仅选择具有除0或空字符串以外的值的列。

1 个答案:

答案 0 :(得分:1)

您可以在以下查询中运行:

db.collection.aggregate([
    { $match: { _id: ObjectId(...) } },
    {
        $replaceRoot: {
            newRoot: {
                $arrayToObject: {
                    $filter: {
                        input: { $objectToArray: "$$ROOT" },
                        cond: {
                            $and: [
                                { $ne: [ "$$this.v", "" ] },
                                { $ne: [ "$$this.v", 0 ] }
                            ]
                        }
                    }
                }
            }
        }
    }
])

这个想法非常简单:从$objectToArray开始,将所有字段都作为数组。然后,您可以运行$filter删除所有零和空格,并将该数组转换回对象$arrayToObject,将其提升到根级别($replaceRoot)。

Mongo Playground