MongoDB count nested key values once, if they are unique

50 views Asked by At

i try to count nested documents inside a findOne operation in golang.

idForDB := "621101966rf42c24a8f41b87"
ctx, cancel := context.WithTimeout(context.Background(), time.Second * 20)
defer cancel()
options := options.FindOneOptions{
        Projection: bson.M{
            "test":          "$test",
            "count": bson.M{}, // count should placed here
        },
    }
result := clients.MongoClient.Database("somedb").Collection("somecollection").FindOne(ctx, bson.M{"_id": idForDB}, &options)

It should count 3 in this case, because "111" is present twice and "222" is there for only one time.

{
   "test":"other",
   "list":[
      {
         "nesting":{
            "numberForCount":"111"
         }
      },
      {
         "nesting":{
            "numberForCount":"111"
         }
      },
      {
         "nesting":{
            "numberForCount":"222"
         }
      }
   ]
}
0

There are 0 answers