0

In my collection labs I have:

{
    "_id" : ObjectId("57e602ada35ea4db6e4eee27"),
    "areas" : [
        "nanotech",
        "robotics"
    ]
}

My query is: db.labs.find({"_id" : ObjectId("57e602ada35ea4db6e4eee27")},{areas:1})

What I want is to count the elements in the slice but not retrieve the whole slice, anyone know? I'm using the mgo package, which has a great correspondence with golang. Thanks

T. Claverie
  • 11,380
  • 1
  • 17
  • 28
omgj
  • 1,369
  • 3
  • 12
  • 18
  • exactly, well I would just range through and increment a counter, but this loads the whole slice into memory, very inefficient – omgj Sep 25 '16 at 12:09

1 Answers1

1

db.labs.aggregate([
  {$match: {"_id" : ObjectId("57e602ada35ea4db6e4eee27")}},
  {$project: {
      areasCount: {"$size": "$areas"}
    }
  }
])
Amiram Korach
  • 13,056
  • 3
  • 28
  • 30