I have been attempting to merge two collections into a new collection while inserting the resulting data into the new collection.
Here is the code I am using for the merge:
db.users.aggregate(
[{
$lookup: {
from: "posts",
localField: "_id",
foreignField: "_uid",
as: "postsByUser"
}
}])
I am aware that this code returns a new collection/array. Now, I am trying to insert this new array into a new collection using this code:
db.postsByUsers.insert(db.users.aggregate(
[{
$lookup: {
from: "posts",
localField: "_id",
foreignField: "_uid",
as: "postsByUser"
}
}]))
However, the result I am getting in the "postsByUsers" collection is not what I expected. I am seeing additional fields like: _useReadCommands, _cursorid, _batchSize, etc. I am getting the information I need in the field called _batch but it is not as organized as I would like. I want it to be an array with objects inside it, including the postsByUser field at the end to provide all the necessary information. I have tried setting a variable usersPosts equal to the aggregation I performed and looping through each document using
db.postsByUsers.insert(usersPosts)
but nothing seems to happen:
usersPosts.forEach(function(doc){
db.postsByUsers.insertOne(doc)
})
I did manage to obtain the desired result at one point, but I am unsure why. I have tried going back through the code by pressing the up key on the command line, but nothing has replicated the successful outcome. Any assistance is greatly appreciated. Thank you for taking the time to read this!