programing

C# mongodb driver 2.0 - 대량 작업에서 어떻게 뒤집습니까?

linuxpc 2023. 6. 25. 18:32
반응형

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);

이 작업이 진행 중인가요, 의도된 것인가요, 아니면 제가 뭔가 놓치고 있는 것인가요?감사해요.

의 속성을 설정UpdateOneModeltrue를 선택하여 업데이트를 업스트림으로 전환합니다.

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

반응형