0

insert many:

[
  { comments: [{foo:1}, {foo:1}, {foo:1}, {foo:1}] }
  { comments: [{foo:1}, {foo:1}] }
  { comments: [{foo:1}, {foo:1}, {foo:1}, {foo:1}, {foo:1}] }
  { title: 'foo' }
  { comments: [{foo:1}, {foo:1}, {foo:1}, {foo:1}, {foo:1}, {foo:1}] }
]

I am trying to find a method to obtain the length of something from the document.

I would like to know how to obtain the desired result:

[{count: 4}, {count: 2}, {count: 5}, {title: 'foo', count: 0}, {count: 6}]
its9527
  • 3
  • 2
  • Does this answer your question? [MongoDB: count the number of items in an array](https://stackoverflow.com/questions/21387969/mongodb-count-the-number-of-items-in-an-array) – ray Mar 01 '23 at 16:07
  • @ray I tried the method provided in your answer, but encountered an error message that reads, "The argument to $size must be an array, but was of type: missing." I'm not sure how to verify whether the array exists. – its9527 Mar 01 '23 at 16:16
  • Can you post your current attempt? – ray Mar 01 '23 at 16:25
  • @ray https://mongoplayground.net/p/KOAmdltnlh3 – its9527 Mar 01 '23 at 16:28

1 Answers1

0

You can handle the case of missing field by wrapping it with $ifNull

db.collection.aggregate([
  {
    $project: {
      "count": {
        "$size": {
          $ifNull: [
            "$comments",
            []
          ]
        }
      }
    }
  }
])

Mongo Playground

ray
  • 11,310
  • 7
  • 18
  • 42