Hello, @AKASH_SKY! Welcome to the community!
Have a look at this aggregation:
db.your_collection.aggregate([
{
$group: {
_id: null,
usersDocs: {
$push: {
_id: '_id',
first: '$first',
last: '$last',
},
},
addrDocs: {
$push: '$addresses',
},
},
},
// flatten array in $addressDocs prop
{
$set: {
addrDocs: {
$reduce: {
input: '$addrDocs',
initialValue: [],
in: {
$concatArrays: ['$$value', '$$this'],
},
},
},
},
},
]);
The above command will provide you with the result like this:
{
usersDocs: [...],
addrDocs: [...]
}
This is, often, a better structure, as you group group all the objects of the same type in one array:
- one array of users objects
- and another one array is for addresses objects
Such approach, often, is more practical
But, of course, you can get array of mixed objects, by adding in the end of that aggregation pipeline, those stages:
{
$project: {
mixedDocs: {
$concatArrays: ['$usersDocs', '$addrDocs'],
},
},
},
{
$unwind: '$mixedDocs',
},
{
$replaceWith: '$mixedDocs',
},
I am curious, what is the reason, that you want to have an array of mixed objects?