Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query MongoDb collection regarding an array of objects in a Go project

In a Go project I stored some data like this in a MongoDb Collection:

{
    _id:ObjectId("631f0752da589137a71687f6"),
    target: { roomId: '11' }
}

{
    _id:ObjectId("43150752da589137a71687f6"),
    target: { roomId: '12' }
}
.
.
.

I have a target array of objects and I want to check the database that if a roomId in database is equal to one of my array of objects values or not.

My target array of objects:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 userRooms:[{"roomId":"12"}, {"roomId":"13"}, {"roomId":"14"}]
 

I create a new array containing just room Id’s like this:

var roomIds []string
for _, v := range RESPONSE.USERROOMS {
    roomIds = append(roomIds, v.ROOMID)
}

I do it like this:

bson.M{ "target": bson.M{"roomId":bson.M{"$in": roomIds }}}}}})

It doesn’t work. it returns zero results.

>Solution :

To construct a filter for a nested field, use the dot . to designate the field with its full "path":

bson.M{"target.roomId": bson.M{"$in": roomIds}}

Where roomIds should be the slice of IDs, e.g. of type []string or []any, but it should contain the room IDs as strings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading