Search code examples
asp.netmongodbmongodb-.net-drivermongodb-csharp-2.0

Serializing a BsonArray with C# driver


Problem: I have a Mongo document that includes two arrays. One of the arrays is large, with subdocuments. This one serializes with no problem. Another is a simple array of this type:

staffgroups {"Tech","Sales"}

This one will not serialize. I get errors saying it's a BsonArray. The closest I've been able to get to serializing it produces a string. I need a JSON object.

Code time:

public class specialtyGroup
{

    public ObjectId _id { get; set; }
    public string name { get; set; }
    public string location { get; set; }
    public coachConfig config { get; set; }
    public schedules[] coaches { get; set; }
    public BsonArray staffgroups { get; set; }

}

And the webservice:

public void GetGroups()
    {

        var client = new MongoClient();
        var db = client.GetDatabase("MongoTul");
        var coll = db.GetCollection<specialtyGroup>("specialtyGroups");

        string cname = HttpContext.Current.Request.Params["loc"];

        var creatures = coll.Find(b => b.location == cname)
            .ToListAsync()
        .Result;

        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(creatures));
    }

I've tried using aggregation and projecting. I've tried creating an additional class for staffgroups (which works for my complex array). And a few other things. All no good.

Most common error looks like this: Unable to cast object of type 'MongoDB.Bson.BsonString' to type 'MongoDB.Bson.BsonBoolean'.


Solution

  • I spent hours on this before posting here, then after posting I figured it out in 30 mins. Sorry.

    The answer is staffgroups should be "public string[] staffgroups {get; set;}

    So if any other rubes like me have that question, there's the answer.