I have two collection to get data from them, my first collection is posts, and second one is company, I want to list posts, and also its brief details of company (rating, totalReviews), What I have tried so far is:
db.getCollection('posts').aggregate([
{"$match":{
// My match conditions
}},
{"$lookup":{
"from":"companies",
"localField":"company.id",
"foreignField":"_id",
"as":"companyDetails"
}},
{"$match":{
"companyDetails":{"$ne":[]}
}},
{"$project":{
"companyDetails.totalReviews":{"$size":{"$ifNull":["$companyDetails.reviews",[]]}}}}
])
Inside company collection reviews field is an array that contain objects.
"reviews" : [
{
"description" : "Five star company",
"userId" : ObjectId("5a82831c0b74a9276c3f826b"),
"_id" : ObjectId("5a9e6d2c38368b365c22a49d"),
"rating" : 4
},
{
"description" : "The best IT solution company.",
"userId" : ObjectId("5a827d868219d03730085803"),
"_id" : ObjectId("5aacb5335b9f3e52dc99e1f2"),
"rating" : 5
}
],
What I want is get length of this array, for example its 2, but my query always return 1, in case of reviews existence, and 0 for not existence.