MongoDB How to get value from subdocument when field name is unknown

删除回忆录丶 提交于 2019-12-24 17:11:21

问题


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

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.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/21542307/mongodb-how-to-get-value-from-subdocument-when-field-name-is-unknown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!