2

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.

2
  • I think you have to map userRooms to [12, 13, 14] Commented Sep 14, 2022 at 17:25
  • I create an array like you said. but still I get zero results. Its possible you to give me the correct query? Commented Sep 14, 2022 at 17:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.