I am trying to use the MongoDB aggregation query to join ($ search) two collections, and then count the various of all unique values ββin a connected array.
So, my two collections look like this: events -
{ "_id" : "1", "name" : "event1", "objectsIds" : [ "1", "2", "3" ], }
The objects
{ "_id" : "1", "name" : "object1", "metaDataMap" : { "SOURCE" : ["ABC", "DEF"], "DESTINATION" : ["XYZ", "PDQ"], "TYPE" : [] } }, { "_id" : "2", "name" : "object2", "metaDataMap" : { "SOURCE" : ["RST", "LNE"], "TYPE" : ["text"] } }, { "_id" : "3", "name" : "object3", "metaDataMap" : { "SOURCE" : ["NOP"], "DESTINATION" : ["PHI", "NYC"], "TYPE" : ["video"] } }
What I want to go out when I make a $ match for the _id = 1 event I want to join the metaDataMap, and then a clear count of all the keys, like this: Counts for the _id = 1 event
SOURCE : 5 DESTINATION: 4 TYPE: 2
What I still know:
db.events.aggregate([ {$match: {"_id" : id}} ,{$lookup: {"from" : "objects", "localField" : "objectsIds", "foreignField" : "_id", "as" : "objectResults"}} ,{$project: {x: {$objectToArray: "$objectResults.metaDataMap"}}} ,{$unwind: "$x"} ,{$match: {"xk": {$ne: "_id"}}} ,{$group: {_id: "$xk", y: {$addToSet: "$xv"}}} ,{$addFields: {size: {"$size":"$y"}} } ]);
This fails because $ objectResults.metaDataMap is not an array object. Any suggestions on how to solve this or another way to do what I want to do? Also, I do not necessarily know which fields (keys) are in the metaDataMap array. And I do not want to read or include fields that may or may not exist on the Map.