Oğuz KURTCUOĞLU
Oğuz KURTCUOĞLU

Reputation: 143

How to create join with embedded string array in MongoDB .net?

I have two collections Product and Categories. A product can have multiple categories. Product is have a string array for keep category ids (as name Product.Categories).

I want to select products with category details. Note: I'm using MongoDB .Net Driver. Can I do this with Linq query?

Products Collection: `

{
  _id : "product_1",
  title : "Product Title 1",
  categories : ["category_1", "category_2"]
},
{
  _id : "product_2",
  title : "Product Title 2",
  categories : ["category_2"]
}

Categories Collection:

{
  _id: "category_1",
  name : "Category 1 Name",
},
{
  _id: "category_2",
  name : "Category 2 Name",
}

I want to result like below:

{
  _id : "product_1",
  title :"Product Title 1",
  categories : [
     {_id = "category_1", name="Category 1 Name"},
     {_id = "category_2", name="Category 2 Name"},
  ]
},
{
  _id : "product_2",
  title :"Product Title 2",
  categories : [
     {_id = "category_2", name="Category 2 Name"},
  ]
}

Upvotes: 0

Views: 234

Answers (1)

ntohl
ntohl

Reputation: 2125

It's basically a join. Which is a Lookup aggregate in C# side. I believe you want the following>

public class Category
{
    public string _id { get; set; }
    public string name { get; set; }
}

public class Product
{
    public string _id { get; set; }
    public string title { get; set; }
    public string[] categories { get; set; }
}

public class AggregatedProduct
{
    [BsonElement("_id")]
    public string Id { get; set; }
    [BsonElement("title")]
    public string Title { get; set; }
    [BsonElement("categories")]
    public Category[] Categories { get; set; }
}


string connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);

var db = client.GetDatabase("test");
var products = db.GetCollection<Product>("Products");
var categories = db.GetCollection<Category>("Categories");
var resultOfJoin = products.Aggregate().Lookup(foreignCollection: categories, localField: x => x.categories,
    foreignField: x => x._id, @as: (AggregatedProduct pr) => pr.Categories).ToList();

Upvotes: 2

Related Questions