반응형
C# mongodb driver 2.0 - 대량 작업에서 어떻게 뒤집습니까?
1.9에서 2.2로 마이그레이션했는데 대량 작업 중에는 옵션이 허용되지 않기 때문에 더 이상 실행할 수 없다는 내용의 설명서를 읽고 놀랐습니다.
bulkOps.Add(new UpdateOneModel<BsonDocument>(filter, update));
collection.BulkWrite(bulkOps);
그래야 한다
options.isUpsert = true;
bulkOps.Add(new UpdateOneModel<BsonDocument>(filter, update, options));
collection.BulkWrite(bulkOps);
이 작업이 진행 중인가요, 의도된 것인가요, 아니면 제가 뭔가 놓치고 있는 것인가요?감사해요.
의 속성을 설정UpdateOneModel
true를 선택하여 업데이트를 업스트림으로 전환합니다.
var bulkOps = new List<WriteModel<BsonDocument>>();
// Create and add one or more write models to list
var upsertOne = new UpdateOneModel<BsonDocument>(filter, update) { IsUpsert = true };
bulkOps.Add(upsertOne);
// Write all changes as a batch
collection.BulkWrite(bulkOps);
몽고 컬렉션 제공
IMongoCollection<T> collection
T has Id 필드에 삽입할 레코드를 열거할 수 있습니다.
IEnumerable<T> records
이 스니펫은 대량 업버트를 수행합니다(필터 조건은 상황에 따라 변경될 수 있습니다).
var bulkOps = new List<WriteModel<T>>();
foreach (var record in records)
{
var upsertOne = new ReplaceOneModel<T>(
Builders<T>.Filter.Where(x => x.Id == record.Id),
record)
{ IsUpsert = true };
bulkOps.Add(upsertOne);
}
collection.BulkWrite(bulkOps);
다음은 @Aviko 응답을 기반으로 한 확장 방법입니다.
public static BulkWriteResult<T> BulkUpsert<T>(this IMongoCollection<T> collection, IEnumerable<T> records)
{
string keyname = "_id";
#region Get Primary Key Name
PropertyInfo[] props = typeof(T).GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
BsonIdAttribute authAttr = attr as BsonIdAttribute;
if (authAttr != null)
{
keyname = prop.Name;
}
}
}
#endregion
var bulkOps = new List<WriteModel<T>>();
foreach (var entry in records)
{
var filter = Builders<T>.Filter.Eq(keyname, entry.GetType().GetProperty(keyname).GetValue(entry, null));
var upsertOne = new ReplaceOneModel<T>(filter, entry){ IsUpsert = true };
bulkOps.Add(upsertOne);
}
return collection.BulkWrite(bulkOps);
}
언급URL : https://stackoverflow.com/questions/35687470/c-sharp-mongodb-driver-2-0-how-to-upsert-in-a-bulk-operation
반응형
'programing' 카테고리의 다른 글
Oracle 등록에 문제가 있습니다.MS SQL Server 2012의 SQLCLR 어셈블리로 데이터 액세스 (0) | 2023.06.25 |
---|---|
oracle plsql: XML을 구문 분석하고 테이블에 삽입하는 방법 (0) | 2023.06.25 |
문자열 배열 초기화 (0) | 2023.06.25 |
SQLALCHEMY_TRACK_MODIES를 사용하지 않도록 설정할 수 있는지 어떻게 알 수 있습니까? (0) | 2023.06.25 |
Base64 인코딩 파일을 저장할 SQL 데이터 유형은 무엇입니까? (0) | 2023.06.25 |