0

I'm using MongoDB with Golang.

I have the following struct which my query result will write to:

var slacks []struct {
        Name        string `json:"name"`
        Description string `json:"description"`
        PostCount   int    `json:"postCount"`
    } `json:"slacks"`
}

I have documents in my collection which look like:

type slack struct {
    ID          bson.ObjectId   `bson:"_id"`
    Name        string          `bson:"name"`
    Description string          `bson:"description"`
    Posts       []post          `bson:"posts"`
}

My aim is to count the posts in each slack using a MongoDB query. I've got this so far:

db.C("slacks").Find(&bson.M{"name": &bson.RegEx{
    Pattern: ".*" + searchStr + ".*",
    Options: "i",
}}).Select(&bson.M{
    "name":        1,
    "description": 1,
    "$size":       "posts",
}).All(&slacks)

But {"$size": "posts"} doesn't do the trick.

How can I query the length of an array/slice of struct in a MongoDB query in Golang?

Ari Seyhun
  • 11,506
  • 16
  • 62
  • 109
  • 2
    I'm pretty sure this question has nothing to do with Go. It's just about how to form a MongoDB query. – Jonathan Hall Apr 19 '17 at 17:00
  • I'm trying to complete this task from my Golang program. I added Go just so the answer will help me... thanks for the suggestion though (and the edit...) – Ari Seyhun Apr 19 '17 at 17:01
  • Sure, you're using it in Go, but once you have a working query, you can use it in any language. – Jonathan Hall Apr 19 '17 at 17:03
  • I'm happy with how my question is. – Ari Seyhun Apr 19 '17 at 17:03
  • 1
    Possible duplicate of [How to aggregate sum in MongoDB to get a total count?](http://stackoverflow.com/questions/17044587/how-to-aggregate-sum-in-mongodb-to-get-a-total-count) – Jonathan Hall Apr 19 '17 at 17:04
  • Have you tried `$count` instead of `$size`? – John Weldon Apr 19 '17 at 17:04
  • I've tried these things... the only issue is that `PostCount int \`json:"postCount"\`` might not be actually the field catching the result of the post count. What would the `"$size": "posts"` 's field name be? – Ari Seyhun Apr 19 '17 at 17:12
  • Flimzy, can you just leave my post alone, I'm not trying to sum numbers in an array... – Ari Seyhun Apr 19 '17 at 17:20
  • 1
    [`$size`](https://docs.mongodb.com/manual/reference/operator/aggregation/size/#exp._S_size) is an `aggregate` operator; you can't use it with `find`. – JohnnyHK Apr 19 '17 at 17:46
  • Ok thank you. Would you recommend I select all the posts and count them in my program, or store a new key such as `postCount`? – Ari Seyhun Apr 19 '17 at 17:48
  • 1
    No, use an [aggregation pipeline](https://docs.mongodb.com/manual/aggregation/) for your query instead of `Find`. Your question appears to be a dupe of http://stackoverflow.com/questions/6722850/querying-internal-array-size-in-mongodb – JohnnyHK Apr 19 '17 at 17:52

0 Answers0