Suppose I have a collection with the following data structures:
post col:
{
_id: ObjectId("5fce0e137ff7401634bad2ac")
address: "new york"
description: "this is a great city"
image: "images\0.4644859674390589-gikiguk.jpg"
userId: "5fcdcd8487e37216bc82171b"
}
user col:
{
_id: ObjectId("5fcdcd8487e37216bc82171b")
name: "jack"
profile: {image: "images\0.4644859674390589-dofowfg.jpg", description: "be happy dude"}
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="196d7c6a6d596d7c6a6d377a7674">[email protected]</a>"
password: "2a$12$gzRrY83QAjwLhdyvn3JQ2OcMj3XG65.BULva4cZqcuSxDhhMbSXCq"
}
likesComments col:
{
_id: ObjectId("5fce0e191ff7301666kao2xc")
likes: {quantity: 1, likes: [{isActive: true, userId: "5fcdcd8487c31216cc87886r"}]}
comments: {quantity: 1, comments: [{userId: "5fcdcd8487c31216cc87886r" , comment: "awesome city"}]}
postId: "5fce0e137ff7401634bad2ac"
}
The scenario involves searching through all posts belonging to a specific user by their userId, retrieving post data from the posts collection, performing a $lookup operation on the users collection to gather user information, and then using postId to look up associated data in the likesComments documents. However, when a post has no likes or comments, the queries return an empty array, but they function properly if there are likes and comments present.
The desired output should resemble the structure below:
[
{
postId: '5fce0e137ff7401634bad2ac',
location: 'shiraz',
description: 'this is a greate city',
image: 'images\\0.4644859674390589-gikiguk.jpg',
userId: '5fcdcd8487e37216bc82171b',
name: 'mohammad',
profile: 'images\\0.6093033055735912-DSC_0002_2.JPG',
comments: { quantity: 1, comments: [{userId: "...", name: "...", profile: "...", comment: "..."}] },
likes: {quantity: 1, [{userId: "...", name: "...", profile: "..."}]}
}
]
query:
I am aware that my query contains errors, but I am unable to identify them at the moment.
db.collection("posts")
.aggregate([
{ $match: { userId: { $in: users.map(u => u) } } },
{
$project: {
_id: 0,
userId: { $toObjectId: "$userId" },
postId: { $toString: "$_id" },
location: "$address",
description: "$description",
image: "$image"
}
},
...
])
.toArray();