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.

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.