0

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.

2
  • can you show me the query which return's you 1 as the array length Commented Mar 17, 2018 at 9:25
  • @Kannan Query that I posted in my question return reviews length 1 for that data, but as you see my reviews array has two object. Commented Mar 17, 2018 at 9:28

1 Answer 1

1

You can try below project stage.

Since lookup returns array use $let to get company detail document followed by projection to output reviews.

Rest of the code stays same.

{
  "$project": {
    "companyDetails.totalReviews": {
      "$size": {
        "$ifNull": [
          {
            "$let": {
              "vars": {
                "companyDetailOne": {
                  "$arrayElemAt": [
                    "$companyDetails",
                    0
                  ]
                }
              },
              "in": "$$companyDetailOne.reviews"
            }
          },
          []
        ]
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It has a syntax error, unexpected string in "in":"$$companyDetailOne.reviews" }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.