Search code examples
c#mongodbmongodb-.net-driver

Get by Id when Id is in another collection's document using C# and MongoDB


I have two collections: Networks and UserNetworks.

In the userNetworks collection I have a userId as Id field and array of networks Ids that belongs to it.

I want to run a query which returns all the networks from Networks collection where networkId is in the given UserId's networks array.

I really want to avoid two queries, one to get the list of networks Ids and the other to fetch the networks themselves. I can't find a decent answer.


Solution

  • What you looking for is called a join and MongoDB doesn't support joins. You can't do what you want in a single query.

    You can do a "join on client" by going through one collection each documet at a time and querying the second collection. Or you can load one (or both) collection to the client instead of going back and forth.