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
CodePudding user response:
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"
]
}
]