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?

11
  • 2
    I'm pretty sure this question has nothing to do with Go. It's just about how to form a MongoDB query. Commented Apr 19, 2017 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...) Commented Apr 19, 2017 at 17:01
  • 1
    Possible duplicate of How to aggregate sum in MongoDB to get a total count? Commented Apr 19, 2017 at 17:04
  • 1
    $size is an aggregate operator; you can't use it with find. Commented Apr 19, 2017 at 17:46
  • 1
    No, use an aggregation pipeline for your query instead of Find. Your question appears to be a dupe of stackoverflow.com/questions/6722850/… Commented Apr 19, 2017 at 17:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.