Search code examples
mongodbgomgo

Mongodb, golang. Can i count an slice/map without loading data into memory?


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


Solution

  • db.labs.aggregate([
      {$match: {"_id" : ObjectId("57e602ada35ea4db6e4eee27")}},
      {$project: {
          areasCount: {"$size": "$areas"}
        }
      }
    ])