MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

How to get two collections at same time

i am getting two collection in two calls , is it possible t get both in one call.

var varrec = database.GetCollection(“abc”).AsQueryable().Where(w => w.BridgeId == “BkN”).ToList();

var varrec1 = database.GetCollection(“extabc”).AsQueryable().Where(w => w.BridgeId == “BkN”).ToList();

Hi Rajesh, It’s not possible to mix two collections in a single call, but I’m curious as to why you would want too?

You should check to see if you could use the $lookup aggregation stage.

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

1 Like

after getting two collections i write a linq query to fillter few records by joining these two collections on bridgeid and some other clause. for ease i have just given bridgeid here.

so if it is possible to write linq query to get those records which are exiting in both tables based on bridgid then also we are good to go.

i am using c# mongo driver to get to mongo pls give one dummy example of $loopup through c#

@Rajesh_Yadav, here’s a link to the MongoDB C# driver documentation for $lookup. They have a couple of examples there that might be of help. I’ve not used the C# driver, but generally the MongoDB documentation is good and a great place to start.

I also have no experience with c#.

You could also use Compass to build your aggregation and then export to c#. I usually build them with Compass, however I seldom export them. I keep them in resource files (java) and I load them at runtime. This way I do not need to recompile and I can use the same file in the shell and in node. One of my idea is to store them in MongoDB directly in a library collection this was they are available to all my processes. But I am not there yet. That is one of the beauty of it. It is a document, an array of document, so it can be stored in a collection.

1 Like

thank you, more thing

var query = from p in collection.AsQueryable()
            join o in otherCollection on p.Name equals o.Key into joined
            select new { p.Name, AgeSum: joined.Sum(x => x.Age) };

q1) in otherCollection, do i have to put .AsQueryable() like following
otherCollection.AsQueryable() or it sould be only otherCollection

q2) in above query we write collection.AsQueryable() , does it get the data at the very time or it executes the whole query at once, that is , the fillter is applied in the database it self and it gets filltered data from the database or it gets the data of both collection in c# from the database and then applys the fillter ( on p.Name equals o.Key) on the caller side.

q3) this query does not have .ToList(), is it required to put it, if i want to execute it at whole query level.