[英]Avoiding duplicates when inserting multiple data into MongoDB
Hi I want to insert multiple data and avoid duplicates in my programme.嗨,我想在我的程序中插入多个数据并避免重复。 I have implemented the code to insert multiple data to mongoDB using asp.net core web api and it's working fine.
我已经实现了代码,使用 asp.net 核心 web Z8A5DA52ED126447D8AAZ7 将多个数据插入 mongoDB 并且工作正常。 I tried so many things but still I couldn't find a way to avoid duplicate records when inserting multiple records.
我尝试了很多东西,但仍然找不到在插入多条记录时避免重复记录的方法。 Can you guys help me please:)
你们能帮帮我吗:)
I want to avoid inserting duplicates by using employeeid.我想避免使用employeeid 插入重复项。
this is my controller这是我的 controller
using HelloApi.Models;
using HelloApi.Services;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace HelloApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class EmployeeController : ControllerBase
{
private readonly EmployeeService _employeeService;
public EmployeeController(EmployeeService employeeService)
{
_employeeService = employeeService;
}
//.....................................Create..............................................
public Task Create(IEnumerable<Employee> employees)
{
return _employeeService.Create(employees);
}
}
}
This is my model class这是我的 model class
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.ComponentModel.DataAnnotations;
namespace HelloApi.Models
{
public class Employee
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[Key]
public string Id { get; set; }
[Required]
[BsonElement("employeeid")]
public string employeeid { get; set; }
[Required]
[BsonElement("firstname")]
public string firstname { get; set; }
[Required]
[BsonElement("lastname")]
public string lastname { get; set; }
[Required]
[BsonElement("age")]
public int age { get; set; }
[Required]
[BsonElement("address")]
public string address { get; set; }
[Required]
[BsonElement("telephone")]
public int telephone { get; set; }
}
}
This is my service class这是我的服务 class
using HelloApi.Models;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HelloApi.Services
{
public class EmployeeService
{
private readonly IMongoCollection<Employee> _employee;
public EmployeeService(IHelloApiDatabaseSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_employee = database.GetCollection<Employee>(settings.employeeCollectionName);
}
//.....................................Create..............................................
public Task Create(IEnumerable<Employee> employees)
{
return _employee.InsertManyAsync(employees);
}
}
}
This is the POST request in Postman and it is working fine but submit duplicates.这是 Postman 中的 POST 请求,它工作正常,但提交重复。
Really appreciate if you guys can help me with this:)
如果你们能帮助我,真的很感激:)
It seems you need to create unique index on employeeId field to avoid duplicates:看来您需要在 employeeId 字段上创建唯一索引以避免重复:
db.employee.createIndex( { "employeeId": 1 }, { unique: true } )
I think you need to add an extra step to declare your Id field as a Primary Key.我认为您需要添加一个额外的步骤来将您的 Id 字段声明为主键。
[Key]
should only work for RDBMS. [Key]
应该只适用于 RDBMS。 For MongoDB i found another post here to define a field as a unique key.对于 MongoDB,我在这里找到了另一篇文章,将字段定义为唯一键。
(Actually MongoDB doesn't really allow for a Primary Key besides the auto-generated '_id' field, afaik, but you can create unique keys. ) (实际上 MongoDB 除了自动生成的 '_id' 字段 afaik 之外,实际上并不允许主键,但您可以创建唯一键。)
Try looking through the answers posted here: How to set a primary key in MongoDB?尝试查看此处发布的答案: 如何在 MongoDB 中设置主键?
This Might be helpful.这可能会有所帮助。 Use below
InsertORUpdateEmployee
function to find and update using employeeid.使用下面
InsertORUpdateEmployee
function 使用employeeid 查找和更新。
public Task<string> Create(IEnumerable<Employee> employees)
{
return Task.Run(() =>
{
return InsertORUpdateEmployee(employees);
});
}
//Insert or Update Employees
private string InsertORUpdateEmployee(IEnumerable<Employee> employees)
{
try
{
foreach (Employee emp in employees)
{
var empId = emp.employeeid;
var DB = Client.GetDatabase("Employee");
var collection = DB.GetCollection<Employee>("EmployeeDetails");
//Find Employee using employeeid
var filter_id = Builders<Employee>.Filter.Eq("employeeid", empId);
var entity = collection.Find(filter_id).FirstOrDefault();
//Insert
if (entity == null)
{
collection.InsertOne(emp);
}
else
{
//Update
var update = collection.FindOneAndUpdateAsync(filter_id, Builders<Employee>.Update
.Set("firstname", emp.firstname)
.Set("lastname", emp.lastname)
.Set("age", emp.age)
.Set("address", emp.address)
.Set("telephone", emp.telephone));
}
}
return "Insert or Updated Succesfully";
}
catch (Exception ex)
{
return ex.ToString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.