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.
To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.
MongoDB provides different types of comparison query operators and $in operator is one of them. This operator is used to select those documents where the value of the field is equal to any of the given value in the array.
Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With