MongoDB How to get value from subdocument when field name is unknown
I'm trying to get data from one or more subdocuments, but I don't know the name of the field that the subdocument will contain. Here are some examples of what documents look like.
- https://github.com/vz-risk/VCDB/blob/master/data/json/0C5DE044-B9B4-408D-9E65-D367EED12AB2.json
- https://github.com/vz-risk/VCDB/blob/master/data/json/064F5887-C2DA-4139-B3AA-D55906F8C30A.json
I would like to get actions for these incidents, so in the case of the first I would like to get action.malware.variety and action.social.variety. In the second example, this would be action.hacking.variety and action.malware.variety. So the problem is that I don't know which field the subdocument will contain. It could be one of hackers, malware, social, bugs, abuse, physical and environmental.
So, I would like to expand this field and do something with the key name. Is this something that can be done using aggregation or do I need to switch to mapReduce?
source to share
You seem to be talking about a case where you are not sure if all the hacky, social, or small parts are correct. I think you want $ project to use $ ifNull first 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"}
])
This should provide you with documents with something in each of these values. An example is roughly the same as for any of the possible values.
source to share