zrbecker
zrbecker

Reputation: 1592

How do a merge multiple fields into a single array in an aggregation?

I have data that has user primary keys in "user.pk", and "usertags.user.pk".

[
  {
    _id: ObjectId("62015250cb18d3cadb32c38e"),
    user: { pk: '7485070525' },
    usertags: [ { user: { pk: '334777488' } } ]
  },
  {
    _id: ObjectId("62015250cb18d3cadb32c38f"),
    user: { pk: '334777488' },
    usertags: [
      { user: { pk: '7485070525' } },
      { user: { pk: '271738610' } },
      { user: { pk: '31961021' } }
    ]
  }
]

I am looking to aggregate all this data into a single list of all distinct user primary keys, so the result for the data above would be something like { _id: null, user_pks: [7485070525, 334777488, 271738610, 31961021] }

I tried using the $group aggregation, but I can't figure out how to merge "user.pk", and "usertags.user.pk". Can anyone help me with that?

Edit: This is the closest I've gotten, which puts users and usertags in separate lists.

db.collection.aggregate([
  { $unwind: "$usertags" },
  { $group: { _id: null, users: { $push: "$user.pk" }, usertags: {$push: "$usertags.user.pk" } } },
])

Upvotes: 1

Views: 2491

Answers (1)

1sina1
1sina1

Reputation: 1086

you can do this:

test it here mongodb playground

db.collection.aggregate([
  {
    $group: {
      _id: null,
      user_pk: {
        $push: "$user.pk"
      },
      user_sub_pk: {
        $push: "$usertags"
      }
    },
    
  },
  // flattern array in user_sub_pk
  {
    $set: {
      user_sub_pk: {
        $reduce: {
          input: "$user_sub_pk",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this"
            ],
            
          },
          
        },
        
      },
      
    },
    
  },
  {
    $project: {
      user_pks: {
        $concatArrays: [
          "$user_pk",
          "$user_sub_pk.user.pk"
        ],
        
      },
      
    },
    // remove duplicate items
    {
    "$project": {
      "user_pks": {
        "$setUnion": [
          "$user_pks",
          []
        ]
      }
    }
  }
    
  }
])

update: refactored by @zrbecker

db.collection.aggregate([
  {
    $group: {
      _id: null,
      users: {
        $push: "$user.pk"
      },
      usertags: {
        $push: "$usertags.user.pk"
      }
    }
  },
  {
    $project: {
      users: {
        $setUnion: [
          "$users",
          {
            $reduce: {
              input: "$usertags",
              initialValue: [],
              in: {
                $concatArrays: [
                  "$$value",
                  "$$this"
                ]
              }
            }
          }
        ]
      }
    }
  }
])

Upvotes: 1

Related Questions