I have been using mongoose ODM with Nodejs environment, during my development I faced such problem. I need to get a list of docs and perform some aggregation operations on these docs. In order to get specific docs I used $match aggregation, but it does not work, I have tried to use without $match stage, so it worked (it returned some docs), but I have to specify exact field and I used match, but it returns an empty array. My pipeline below (using mongoose):
const comments = await Comments.aggregate([
{
'$match': {
'article_id': Types.ObjectId(id)
}
},
{
'$unwind':
{
path: '$replies'
}
},
{
'$lookup': {
from: 'users',
localField: 'replies.sender',
foreignField: '_id',
'pipeline': [
{'$project': {'first_name': 1, 'last_name': 1, '_id': 0}}
],
as: 'replies.sender'
}
},
{
'$unwind': {
path: '$replies.sender'
}
},
{
'$group': {
'_id': '$_id',
'replies': {
'$push': '$replies'
}
}
},
{
'$lookup': {
from: 'comments',
localField: '_id',
foreignField: '_id',
as: 'commentDetails'
}
},
{
'$unwind': {
path: '$commentDetails'
}
},
{
'$addFields': {
'commentDetails.replies': '$replies'
}
},
{
'$replaceRoot': {
'newRoot': '$commentDetails'
}
},
{
'$unwind':
{
path: '$replies'
}
},
{
'$lookup': {
from: 'users',
localField: 'replies.receiver',
foreignField: '_id',
'pipeline': [
{'$project': {'first_name': 1, 'last_name': 1, '_id': 0}}
],
as: 'replies.receiver'
}
},
{
'$unwind': {
path: '$replies.receiver'
}
},
{
'$group': {
'_id': '$_id',
'replies': {
'$push': '$replies'
}
}
},
{
'$lookup': {
from: 'comments',
localField: '_id',
foreignField: '_id',
as: 'commentDetails'
}
},
{
'$unwind': {
path: '$commentDetails'
}
},
{
'$addFields': {
'commentDetails.replies': '$replies'
}
},
{
'$replaceRoot': {
'newRoot': '$commentDetails'
}
},
{
'$lookup': {
'from': 'users',
'localField': 'user_id',
'foreignField': '_id',
'pipeline': [
{'$project': {'first_name': 1, 'last_name': 1, '_id': 0}}
],
'as': 'user'
}
},
{
'$unwind': '$user'
},
]).sort({'date_time': 'descending'})