Search code examples
c#mongodblinqnosqlmongodb-.net-driver

LINQ query to push an item to the array of a Mongo Document


I want to push a ProductPhoto inside the Product using LINQ. Here is my model:

public class Product
{
   public string Id { get; set; }
   public string Name { get; set; }
   public string Detail { get; set; }
   public List<ProductPhoto> ProductPhotos { get; set; }
}

public class ProductPhoto
{
   public string Id { get; set; }
   public string Url { get; set; }
}

How can I achieve this with the LINQ query? I am expecting the result to be something like this.

{
    _id: ObjectId('602d2149e773f2a3990b47f5'),
    Name: 'Some name',
    Detail: 'Some description',
    ProductPhotos: [
      { _id: ObjectId('602d2149e773f2a3990b47f5'), Url: 'Some URL' }
    ] 
}

Next time when I add a new ProductPhoto, then there will be two elements.

Thanks!


Solution

  • Here is the solution to similar question:

    How to 'Find And Push' element in an array inside of another array in a document using LINQ to MongoDb

    You can achieve this with something like this:

    var filterBuilder = Builders<Product>.Filter;
    var filter = filterBuilder.Eq(x => x.Id, productId);
    var updateBuilder = Builders<Product>.Update;
    var update = updateBuilder.Push(doc => doc.ProductPhotos, productPhoto);
    Products.UpdateOneAsync(filter, update);