MongoDB字段名称未知时如何从子文档获取值 [英] MongoDB How to get value from subdocument when field name is unknown

查看:106
本文介绍了MongoDB字段名称未知时如何从子文档获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一个或多个子文档中获取数据,但是我不知道将保存该子文档的字段名称.这是文档外观的一些示例.

I'm trying to get data from one or more subdocuments but I don't know the name of the field that will hold the subdocument. Here are some examples of what the documents look like.

  1. https: //github.com/vz-risk/VCDB/blob/master/data/json/0C5DE044-B9B4-408D-9E65-D367EED12AB2.json
  2. https: //github.com/vz-risk/VCDB/blob/master/data/json/064F5887-C2DA-4139-B3AA-D55906F8C30A.json
  1. https://github.com/vz-risk/VCDB/blob/master/data/json/0C5DE044-B9B4-408D-9E65-D367EED12AB2.json
  2. https://github.com/vz-risk/VCDB/blob/master/data/json/064F5887-C2DA-4139-B3AA-D55906F8C30A.json

我希望获得针对这些事件的操作种类,因此对于第一个事件,我希望获得action.malware.variety和action.social.variety.在第二个示例中,将是action.hacking.variety和action.malware.variety.所以问题是我不知道哪个字段将保存子文档.它可能是黑客,恶意软件,社交,错误,滥用,物理和环境之一.

I would like to get the action varieties for these incidents, so in the case of the first one I would like to get action.malware.variety and action.social.variety. In the second example it would be action.hacking.variety and action.malware.variety. So the problem is that I don't know what field is going to hold the subdocument. It could be one of hacking, malware, social, error, misuse, physical, and environmental.

所以我想$ unwind该字段,并用键名做一些事情.这是聚合可以完成的事情,还是我需要切换到mapReduce?

So I would like to $unwind that field and do some stuff with the key name. Is this something that can be done with aggregation or do I need to switch over to mapReduce?

推荐答案

您似乎在谈论一种情况,即您不确定所有黑客,社交或恶意软件部分是否都正确.我认为您想先 $ project http://docs.mongodb.org/manual/reference/operator/aggregation/ifNull/"rel =" nofollow> $ ifNull 运算符,如下所示:

You seem to be talking about a case where you are not sure if all of the hacking, social or malaware parts are there right. I think you want $project first using the $ifNull operator as in:

db.stuff.aggregate([
    {$project: 
        { 
           hacking: {$ifNull: ["$action.hacking.variety",[null]]},
           social: {$ifNull: ["$action.social.variety",[null]]},
           malware: {$ifNull: ["$action.malware.variety",[null]]}
        }
   },
   {$unwind: "$hacking"},
   {$unwind: "$social"},
   {$unwind: "$malware"}
])

这应该使您的文档在每个值中都包含一些内容. 与任何可能的值列表几乎相同.

That should give you documents with something in each of those values. Sort of pretty much the same with any of your possible list of values.

这篇关于MongoDB字段名称未知时如何从子文档获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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