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.

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?

+1


source to share


1 answer


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.

+3


source







All Articles