1

I have a MongoDB collection that looks similar to this:

{
  _id : 1,
  key : "key1",
  value : [ "val11", "val12"]
}
{
  _id : 2,
  key : "key2",
  value : [ "val21", "val22", "val23"]
}

I'd like to get a List of MyObjects ( MyObject consisting of two string properties name and category) from this collection that'd look like this:

[{Category: "key1", Name: "val11"}, {Category: "key1", Name:"val12"}, 
{Category: "key2", Name: "val21"}, {Category:"key2",Name:"val22"}, {Category: "key2", Name: "val23"}]

public class MyObject
{
    public string Name{ get; set; }
    public string Category { get; set; }
}

I would be very grateful if someone could point me into the right solution, preferably using LINQ.

Darkersan
  • 21
  • 2

1 Answers1

1

You can use aggregation framework and you need two steps: $unwind to transform an array to separate documents and $project to rename properties. In C# if you don't want to introduce additional class for the original form of your data you can use BsonDocument:

var col = mydb.GetCollection<BsonDocument>("col");

var projection = new BsonDocument() {
    { nameof(MyObject.Category), $"$key" },
    { nameof(MyObject.Name), $"$value" },
    { "_id", 0  }
};

var result = col.Aggregate().Unwind("value")
    .Project<MyObject>(projection).ToList();
mickl
  • 48,568
  • 9
  • 60
  • 89