Golang,MongoDB,使用$ in在数组属性中查找带有一个字符串的所有元素时遇到问题

Golang,MongoDB,使用$ in在数组属性中查找带有一个字符串的所有元素时遇到问题

问题描述:

I am trying to find all users in a MongoDB collection that contains a username string in the friends array. I am using Golang with the mgo driver.

   type User struct {
    ...
        Friends        []string    `json: friends bson:"friends,omitempty"` 
    ...
    }

    ...
    // username is a string
    arr := []string{username}

    err := c.Find(bson.M{"friends": {"$in": arr}}).All(&users)
    ...

I get this error: http: panic serving [::1]:56358: assignment to entry in nil map

Any help would be greatly appreciated.

You are using "$in" wrong. You aren't initialising inner map. You are supposed to use it like this:

err := c.Find(bson.M{"friends": bson.M{"$in": arr}}).All(&users)