Search code examples
c#mongodbjoinlookup

Use c# to test the lookup of mongodb, but find the result after join is always blank


Recently, I used c# to test the lookup of mongodb, but found that the value of the parameter "JoinResult" is always blank after the join. I don't know where I wrote it wrong?

MongoClient client = new MongoClient("mongodb://localhost:27017");
 MongoDatabaseBase? db = client.GetDatabase("Test") as MongoDatabaseBase;
 var ExpertCaseCollection = db.GetCollection<ExpertCase>("ExpertCase");
 var BuildCaseTwoCollection = db.GetCollection<BuildCaseTwo>("BuildCaseTwo");
 var q = ExpertCaseCollection.Aggregate()
                    .Match(Builders<ExpertCase>.Filter.Gte(u => u.SelfMail, "111@yahoo.com.tw"))                   
                    .Lookup(
                    foreignCollectionName: "BuildCaseTwoCollection",
                    localField: "CaseID",
                    foreignField: "CaseID",
                    @as: "JoinResult");                   
            var lzToLost = q.ToList();
    
        Test.ExpertCase=>
           _id:648407489546f5903b618752
      SelfMail:"111@yahoo.com.tw"
  ProposerMail:"test@yahoo.com.tw"
        CaseID:"111"
          Date:"202301010812"
    Test.BuildCaseTwo=>
            _id:6485338f2635ca68a27633e1
       SelfMail:"222@yahoo.com.tw"
     JoinExpert:"111@yahoo.com.tw,333@yahoo.com.tw"
         CaseID:"111"
      CaseTiele:"TestProject"
           Date:"202301010812"

Solution

  • I think this line:

    foreignCollectionName: "BuildCaseTwoCollection",
    

    Should be:

     foreignCollectionName: "BuildCaseTwo",
    

    As that's the name you specify here:

    Test.BuildCaseTwo=>
    

    Seperate note: I haven't used mongoDb from C# in a while, but you aren't using the BuildCaseTwoCollection variable that you declare. I can't remember how to specify a declared collection as part of the aggregate query, and the mongoDb docs were not helpful at a quick glance