0

For the given structure I need to find out the count of the likes array based on the unique slug value

{
  "_id" : ObjectId("4e8ae86d08101908e1000001"),
  "name" : ["Name"],
  "likes" : ["emp1"],
  "slug": 'slugabcd'
 }
{
  "_id" : ObjectId("4e8ae86d08101908e1000002"),
  "name" : ["Another ", "Name"],
  "likes" : ["emp1","emp2","emp4"],
  "slug": 'slugxyz'
}
{
      "_id" : ObjectId("4e8ae86d08101908e1000002"),
      "name" : ["Another ", "Name"],
      "slug": 'slugpqr'
}

Here is my code but not working

db.blog.aggregate({slug:"slugxyz"},{$project:{NumberOfItemsInArray:{$size:"likes"}}}).count();

How can we achieve this?

2
  • Will more than one document have the same slug value? If not you can just get length of array right? Commented Jun 24, 2021 at 5:03
  • 1
    all the docs slug should be unique, how to get the length of likes Commented Jun 24, 2021 at 5:06

2 Answers 2

1

Without using any query stage:

db.blog.aggregate({$project:{slug : "$slug", numberOfLikes:{$size:"$likes"}}})
Sign up to request clarification or add additional context in comments.

1 Comment

db.blog.aggregate({$project:{slug : "$slug", numberOfLikes:{"$size":{"$ifNull":["$likes",[]]}}}}) I hope this should work more. Thanks for looking into this
0

Try the following:

const pipeline = [
{ 
 $group: {
    _id: "$slug",
    likesCount: {$sum: {$size: "$likes"}}
 }
]

Here we are grouping by the unique "slug" value and counting the size of "likes" array field.

Comments

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.