简体   繁体   中英

c# MongoDB select list of fields from a field

Let's say i have this document structure stored in my MongoDB database.

{
    "_id" : ObjectId("54f131f3c4ca7b044eb11171"),
    "services" : "gegsg",
    "validCertificateOrLicense" : {
        "title" : "asfasf",
        "number" : "fasfsdf",
        "dateIssued" : "fsdffsdfsdf",
        "validUntil" : "fsdfsdfd",
        "issuingAgency" : "fsdfsd"
    }
}

I wanted to list those fields in my Binding to be used on my DataGrid, I have tried to use the solutions posted on several stack questions. But none of them worked, i tried to check using Console.WriteLine(BindList.Count) to check whether the query works.

class facultyData
{

    public ObjectId _id { get; set; }
    public string services { get; set; }
    public List<certification> validCertificateOrLicense { get; set; }

}

class certification
{
    public string title { get; set; }
    public string number { get; set; }
    public string dateIssued { get; set; }
    public string validUntil { get; set; }
    public string issuingAgency { get; set; }
}

This is one of solution that i have tried.

  var query =  collection.AsQueryable<facultyData>()
             .Where(c => c.validCertificateOrLicense.Any(d => d.stores.Count() == 1);

Or maybe there's a problem with my ToList code

List<facultyData> acadList = query1.ToList<facultyData>();   
        BindingList<facultyData> acadBinding = new BindingList<facultyData>(acadList);

我认为这会奏效

 var acadList = Database.GetCollection<facultyData>("facultyData").AsQueryable().Where(f => f.validCertificateOrLicense.Any()).ToList();

Your class facultyData contains a list of certifications in the validCertificateOrLicense field. However your document structure in the DB only contains a single certificate in the validCertificateOrLicense field.

If your document structure in the DB is as follows then your query should work

{
    "_id" : ObjectId("54f131f3c4ca7b044eb11171"),
    "services" : "gegsg",
    "validCertificateOrLicense" : [{
        "title" : "asfasf",
        "number" : "fasfsdf",
        "dateIssued" : "fsdffsdfsdf",
        "validUntil" : "fsdfsdfd",
        "issuingAgency" : "fsdfsd"
    }]
}

Note - the validCertificateOrLicense field now contains an array of certification sub documents.

Alternatively you could change your c# entity to match the existing document structure in the DB. Your facultyData object would look as follows

class facultyData
{

    public ObjectId _id { get; set; }
    public string services { get; set; }
    public certification validCertificateOrLicense { get; set; }

}

Note - now the validCertificateOrLicense field only contains a single certification document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM