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:
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.
CodePudding user response:
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 string
s.