skip to Main Content

I have a list of collection like the following in mongodb

   { _id: ObjectId("6087feeef467a4320883daf3"),
     name: 'group 1',
     admins: ['adam', 'ken']
   }

   { _id: ObjectId("2087feeef467a4320883daf3"),
     name: 'group 2',
     admins: ['rebecca']
   }

   { _id: ObjectId("9987feeef467a4320883daf3"),
     name: 'group 3',
     admins: []
   }

I need to extract out all the admins, the end result would be something like this:

[
  'admin',
  'ken',
  'rebecca'
]

How can i do that, i stuck at this part:

db.data.find({ admins: { $exists: true, $not: {$size: 0} } })

This will show all collections, but i just need the list

2

Answers


  1. You can do something like this

    db.data.aggregate([
      {$unwind: "$admins"},
      {$project:{_id:0}}
    ]).map(x => x.admins);
    

    Result

    [
        "adam",
        "ken",
        "rebecca"
    ]
    

    enter image description here

    Login or Signup to reply.
  2. The proper way of doing so using single query is unwinding the array of admins and adding them to a new set.

    db.collection.aggregate([
      {
        $unwind: "$admins"
      },
      {
        $group: {
          _id: null,
          adminsSet: {
            $addToSet: "$admins"
          }
        }
      }
    ])
    

    The end result will be the following so you could extract your flattened array:

    [
      {
        "_id": null,
        "adminsSet": [
          "ken",
          "rebecca",
          "adam"
        ]
      }
    ]
    

    Mongo playground ref: https://mongoplayground.net/p/LFYsqHdTucN

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search