Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang,MongoDB, Having issues using $in to find all elements with one string in there array property

Tags:

mongodb

go

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.

like image 501
Kody Doherty Avatar asked May 14 '16 20:05

Kody Doherty


People also ask

How do I find an element in an array in MongoDB?

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.

How do I use $in in MongoDB?

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.

How do I filter an array of objects in MongoDB?

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.


1 Answers

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)
like image 65
khrm Avatar answered Oct 11 '22 22:10

khrm