MongoDB: how to combine two different data structure to one

Viewed 25

Here is my collection:

db.sites_people.find({person_id: ObjectId('62df5722d361708c1f0a7e9f')}, {user_groups: 1}):
[
    {
        '_id': { '$oid': '62df5769b6f6345d3e91130d' },
        'user_groups': [
            {
                'id': { '$oid': '62df5769d361708c1f0a7ea1' },
            },
        ],
    },
    {
        '_id': { '$oid': '62df584eb6f6345d3e91138a' },
        'user_groups': [
            { '$oid': '62df5769d361708c1f0a7ea1' },
        ],
    },
];

As you can see, there are two different-structure under user_groups .

I try to use $ifNull to combine the user_groups, but it's not work.

db.sites_people.aggregate([
    { $match: { person_id: ObjectId('62df5722d361708c1f0a7e9f') } },
    { $project: { user_groups: { $ifNull: ['$user_groups.id', '$user_groups'] } } },
]);
[
    {
        '_id': { '$oid': '62df5769b6f6345d3e91130d' },
        'user_groups': [
            { '$oid': '62df5769d361708c1f0a7ea1' },
        ],
    },
    {
        '_id': { '$oid': '62df584eb6f6345d3e91138a' },
        'user_groups': [],
    },
];

How can I get the result like this:

[
    {
        '_id': { '$oid': '62df5769b6f6345d3e91130d' },
        'user_groups': [
            { '$oid': '62df5769d361708c1f0a7ea1' },
        ],
    },
    {
        '_id': { '$oid': '62df584eb6f6345d3e91138a' },
        'user_groups': [
            { '$oid': '62df5769d361708c1f0a7ea1' },
        ],
    },
];
1 Answers

Best way is to just use $map to convert the arrays, this will also allow you to have unified structures for mixed type arrays ( one element with id and one without ), like so:

db.sites_people.aggregate([
  {
    $match: {
      person_id: ObjectId("62df5722d361708c1f0a7e9f")
    }
  },
  {
    $project: {
      user_groups: {
        $map: {
          input: "$user_groups",
          in: {
            $ifNull: [
              "$$this.id",
              "$$this"
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

Related