MongoDB $setUnion on object ($setUnion but with additional information)

Viewed 854

stackoverflow community, I do not often work with big Arrays of Objects within in mongodb so I have no idea how to solve this problem:

1. i am working within one file, so obviously it's an aggregate witch firstly does an {$match:{"_id" : ObjectId("5c3f5cb04147b3082648278b") }},

2. ok now I have another step that $project + $filter to filter out some objects, but it is not important for this (i think)

  1. I have an array of objects, similar to this

    { "_id": ObjectId(".."), "data": [

    {
      id : 01,
      groupId: 22,
      noteId: 876543
    },
    {
      id : 02,
      groupId: 33,
      noteId: 767676
    },
    {
      id : 03,
      groupId: 22,
      noteId: 876543
    },
    {
      id : 04,
      groupId: 76,
      noteId: 876543
    }
    

    ] }

but with thousands of entries and more values per object.

Every groupId can have any noteId, but the same groups have always the same noteId. The Problem: noteIds can be shared between groups.

I added this

{ $project: {
                "groupIds": {"$setUnion": "$data.groupId"}
            }}

witch gives me all the groupIds but it is very important that I also get all the related noteId's because it is an arbitrary ID in relation with nothing else.

is it possible to somehow union an object by a specified field? or is there another way to solve this? If I maybe filter for Objects with $in($data.groupId, $setUnion('union from above') I still would not know how to only extract the 2 fields that I need.

thanks for your help in advance

H.M.

1 Answers

You can use below aggregation

db.collection.aggregate([
  { "$unwind": "$data" },
  { "$group": {
    "_id": {
      "_id": "$_id",
      "groupId": "$data.groupId"
    },
    "noteIds": {
      "$push": {
        "noteId": "$data.noteId",
      }
    }
  }},
  { "$group": {
    "_id": "$_id._id",
    "data": {
      "$push": {
        "groupId": "$_id.groupId",
        "noteIds": "$noteIds"
      }
    }
  }}
])
Related