[CSHARP-877] How can we select record from two colections from MongoDb? Created: 13/Dec/13  Updated: 05/Apr/19  Resolved: 13/Dec/13

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: 1.8.3
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: tipu moazzam khan Assignee: Robert Stam
Resolution: Done Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Hello,
How can we get result from 2 more or more collections in MongoDb? Lets suppose there are 2 collections, c1 and c2 and they have common attribute name.Now how can I fetch all the doccuments of both colections where name is matching?

Plz help me. i am quite new in MongoDb. our organization is planning to0 purchase subscription but prior to that , i need to submit a poc that have this requirement.

Thanks in advance.

Regards,
Tipu



 Comments   
Comment by Robert Stam [ 13/Dec/13 ]

MongoDB does not support server side joins. The way to do this is to issue two queries. In the first query you get all the matching documents from the first collection. In the second query you get all the matching documents in the second collection.

Here's a code sample using your scenario (collections c1 and c2 with a common "name" field):

var c1 = database.GetCollection<BsonDocument>("c1");
var c2 = database.GetCollection<BsonDocument>("c2");
var query1 = Query.Null; // this matches all documents, replace with an appropriate query
var c1Documents = c1.Find(query1).ToList();
var c1Names = new HashSet<string>(c1Documents.Where(d => d.Contains("name")).Select(d => d["name"].ToString()));
var query2 = Query.In("name", c1Names.Select(n => new BsonString(n)));
var c2Documents = c2.Find(query2).ToList();

Generated at Wed Feb 07 21:38:05 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.