我如何使用最新的MongoDB C#驱动程序根据多个条件删除复杂数组对象的嵌套数组中的元素?

问题描述 投票:0回答:1

总体目标是能够根据用户ID和用户ID对用户进行膳食查询。如果找到该项目,则我只希望删除同时与userid和营养ID匹配的整个元素。

当前,在发布请求中通过邮递员发送请求对象后,我尝试使用C#编写查询的变体以创建构建器对象,然后进行过滤以查找特定的数组对象,最后删除该数组对象如果用户名和粉饼都匹配。最初,我遇到的问题是没有删除整个元素,而是仅嵌套在元素内部的内部数组元素(没有删除,而是重新设置为空值)。但是,现在的问题是,整个数组元素都没有被删除,并且我遇到了以下错误。BsonArraySerializer Error from Visual Studio

有人可以帮我解决这个问题吗?

这里是我要通过邮递员发送的示例对象,我试图将其删除:Sample Postman POST request with Body data

以下是我要删除的数据的示例图像:Sample Image of Json Array Elemet I'm trying to delete

您将需要MongoDb指南针或Atlas,.NET Core 3.1,MongoDB C#驱动程序2.0,Postman和.NET Core 3.1 WebApi项目/解决方案,以帮助解决此问题。] >>

下面是复制问题所需的代码:

Startup.cs

将这行代码添加到此文件的Configuration方法中

services.AddScoped<IMealsRepository, MealsRepository>();

将此行添加到ConfigureServices方法中

services.AddSingleton(sp =>
            sp.GetRequiredService<IOptions<DatabaseSettings>>().Value);

appSettings.json

将这些代码行添加到此文件中

 "DatabaseSettings": {

    "ConnectionString": "your connection string to MongoDb"

}

Database Settings.cs

    public class DatabaseSettings
    {
        public string ConnectionString { get; set; } 
    }

MealPlanModel.cs:

using MongoDB.Bson;

using MongoDB.Bson.Serialization.Attributes;

public class MealPlanModel
{

    #region MealPlanModel fields
    [BsonElement("userid")]
    public int? UserId { get; set; }

    [BsonElement("mealid")]
    public int? MealId { get; set; }

    [BsonElement("mealname")]
    public string MealName { get; set; }

    [BsonElement("mealimage")]
    public string MealImage { get; set; }

    [BsonElement("foods")]
    public FoodModel[] Foods { get; set; }

    [BsonElement("totalcalories")]
    public double TotalCalories { get; set; }

    [BsonElement("totalprotein")]
    public double TotalProtein { get; set; }

    [BsonElement("totalcarbs")]
    public double TotalCarbs { get; set; }


    [BsonElement("totalfat")]
    public double TotalFat { get; set; }

    [BsonElement("totalsugar")]
    public double TotalSugar { get; set; }

    [BsonElement("totalfiber")]
    public double TotalFiber { get;  set; }
    #endregion

    #region MealPlanModel ctor
    public MealPlanModel()
    {

    }

    public MealPlanModel(int userid, int mealid)
    {
        UserId = userid;
        MealId = mealid;
    }
}

MealPlanDto.cs

using MongoDB.Bson;

using MongoDB.Bson.Serialization.Attributes;

using System.Collections.Generic;

public class MealPlanDto

{

    [BsonId]
    public ObjectId Id { get; set; }

    [BsonElement("meals")]
    public List<MealPlanModel> MealPlans { get; set; }
}

**MealsController.cs:**


using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Security.Claims;

using System.Threading.Tasks;

using AutoMapper;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Newtonsoft.Json;

[Route("api/[controller]")]

[ApiController]

public class MealsController : ControllerBase

{


    private readonly IMealsRepository _repo;

    private readonly IMapper _mapper;

    public MealsController(IMealsRepository repo, IMapper mapper)
    {
        _repo = repo;

        _mapper = mapper;

    } 


    [HttpGet, Route("CheckConnection")]

    public async Task<IActionResult> CheckConnection()

    {

        var result = await _repo.CheckConnection();

        if (result == null || result.Count <= 0)

            return BadRequest("Failed to connect to database.");

        return Ok("Database connection was successful");

    }

    [HttpPost("deletecustommeal")]

    public async Task<IActionResult> DeleteCustomMealPlan(int id)

    {

      var requestBody = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
      var mealPlanToDelete = JsonConvert.DeserializeObject<MealPlanModel>(requestBody);
      MealPlanDto deleteMealPlan = new MealPlanDto();
      deleteMealPlan.MealPlans = new List<MealPlanModel>();
      deleteMealPlan.MealPlans.Add(mealPlanToDelete);
      var result = await _repo.DeleteCustomMealPlanById(deleteMealPlan);
      if (!result)
         return BadRequest("Failed to delete meal");
      return Ok("Successfully deleted meal plan");
    }

}

MealsRepository.cs

using Microsoft.Extensions.Configuration;

using MongoDB.Bson;

using MongoDB.Driver;

using System;

using System.Collections.Generic;

using System.Threading.Tasks;

public class MealsRepository : IMealsRepository

{

    private readonly MongoClient _client;

    private readonly IMongoDatabase _database;

    private readonly IMongoCollection<MealPlanDto> _userMealsCollection;

    public MealsRepository(IConfiguration configuration)
    {
        _client = new 
          MongoClient(configuration.GetSection("DatabaseSettings").GetSection("ConnectionString").Value);
        _database = _client.GetDatabase("MealsDb");
        _userMealsCollection = _database.GetCollection<MealPlanDto>("meal");
    }

    public async Task<List<BsonDocument>> CheckConnection()
    {
        List<BsonDocument> list = await _database.ListCollections().ToListAsync();
        var populatedList = (list != null && list.Count > 0) ? list : null;
        return populatedList;
    }

    public async Task<bool> DeleteCustomMealPlanById(MealPlanDto mealPlanToDelete)

    {
        var builder = Builders<MealPlanDto>.Filter;
        var filter = builder.Eq(x => x.MealPlans[0].UserId, mealPlanToDelete.MealPlans[0].UserId);

        var update = Builders<MealPlanDto>.Update.PullFilter(
            p => (IEnumerable<MealPlanModel>)p.MealPlans[0],
            f => f.MealId.Value == mealPlanToDelete.MealPlans[0].MealId);

        try
        {
            await _userMealsCollection.UpdateOneAsync(filter, update);
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Failed to delete meal plan. {ex} occured.");
            return false;
        }
    }

}

总体目标是能够根据用户ID和用户ID对用户进行膳食查询。如果找到该项目,则我只希望删除与两个用户ID都匹配的整个元素...

c# mongodb multidimensional-array .net-core-3.1 mongodb-csharp-2.0
1个回答
0
投票

感谢所有尝试找到上述问题的答案的人,但实际上我找到了一个简单的解决方法

© www.soinside.com 2019 - 2024. All rights reserved.