배열 업데이트
이 페이지의 내용
개요
The .NET/ C# 드라이버 supports the 배열 업데이트 operators and modifiers described in the MongoDB Server manual. To create an UpdateDefinition
객체 for one of these operators, call the corresponding method from the Builders.Update
속성. 다음 섹션에서는 이러한 메서드에 대해 자세히 설명합니다.
After you create an UpdateDefinition
객체, pass it to the UpdateOne()
or UpdateOneAsync()
method. 이러한 메서드에 대한 자세한 내용은 업데이트 1 페이지를 참조하세요.
참고
메서드 오버로드
이 페이지의 많은 메서드에는 여러 오버로드가 있습니다. The examples in this 가이드 show only one definition of each method. For more information about the available overloads, see the API documentation.
샘플 데이터
이 가이드의 예에서는 sample_restaurants
데이터베이스의 restaurants
컬렉션을 사용합니다. 이 컬렉션의 문서는 다음 Restaurant
, Address
, GradeEntry
클래스를 모델로 사용합니다.
public class Restaurant { public ObjectId Id { get; set; } public string Name { get; set; } [ ] public string RestaurantId { get; set; } public string Cuisine { get; set; } public Address Address { get; set; } public string Borough { get; set; } public List<GradeEntry> Grades { get; set; } }
public class Address { public string Building { get; set; } [ ] public double[] Coordinates { get; set; } public string Street { get; set; } [ ] public string ZipCode { get; set; } }
public class GradeEntry { public DateTime Date { get; set; } public string Grade { get; set; } public float? Score { get; set; } }
참고
restaurants
컬렉션 의 문서는 대소문자 명명 규칙을 사용합니다. 이 가이드 의 예제에서는 ConventionPack
를 사용하여 컬렉션 의 필드를 파스칼식 대/소문자로 역직렬화하고 Restaurant
클래스의 속성에 매핑합니다.
사용자 지정 직렬화에 대해 자세히 알아보려면 사용자 지정 직렬화를참조하세요.
이 컬렉션은 Atlas에서 제공하는 샘플 데이터 세트에서 가져온 것입니다. 퀵 스타트를 참조하여 무료 버전의 MongoDB 클러스터를 생성하고 이 샘플 데이터를 로드하는 방법을 알아보세요.
1개의 값 추가
To add one value to the end of an 배열, call the Builders.Update.Push()
method. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
---|---|
| 데이터 유형: |
| 데이터 유형: |
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .Push(restaurant => restaurant.Grades, new GradeEntry() { Date = DateTime.Now, Grade = "A", Score = 96 }); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .Push(restaurant => restaurant.Grades, new GradeEntry() { Date = DateTime.Now, Grade = "A", Score = 96 }); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
팁
푸시 작업 구성
AddToSet()
메서드는 다음 매개 변수를 허용합니다:
Parameter | 설명 |
---|---|
| 데이터 유형: |
| 데이터 유형: |
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; var update = Builders<Restaurant>.Update .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; var update = Builders<Restaurant>.Update .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
여러 값 추가
To add multiple values to an 배열, call the Builders.Update.PushEach()
method. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
---|---|
| 데이터 유형: |
| 데이터 유형: |
| 데이터 유형: |
| 데이터 유형: |
| 데이터 유형: SortDefinition<TItem> |
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} }; var scoreSort = Builders<GradeEntry>.Sort.Descending(g => g.Score); var update = Builders<Restaurant>.Update.PushEach( "Grades", newGrades, position: 0, sort: scoreSort); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} }; var scoreSort = Builders<GradeEntry>.Sort.Descending(g => g.Score); var update = Builders<Restaurant>.Update.PushEach( "Grades", newGrades, position: 0, sort: scoreSort); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
To add multiple values to an 배열, but only if they don't already exist in the 배열, call the Builders.Update.AddToSetEach()
method. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
---|---|
| 데이터 유형: |
| 데이터 유형: |
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); var firstGradeEntries = new List<GradeEntry> { doc.Grades[0], doc.Grades[1] }; var update = Builders<Restaurant>.Update .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); var firstGradeEntries = new List<GradeEntry> { doc.Grades[0], doc.Grades[1] }; var update = Builders<Restaurant>.Update .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
Remove Values
첫 번째 값
To 제거 the first value from an 배열, call the Builders.Update.PopFirst()
method. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
---|---|
| 데이터 유형: |
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .PopFirst(restaurant => restaurant.Grades); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .PopFirst(restaurant => restaurant.Grades); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
마지막 값
Parameter | 설명 |
---|---|
| 데이터 유형: |
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .PopLast(restaurant => restaurant.Grades); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .PopLast(restaurant => restaurant.Grades); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
값의 모든 인스턴스
To 제거 all instances of a specific value from an 배열, call the Builders.Update.Pull()
method. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
---|---|
| 데이터 유형: |
| 데이터 유형: |
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); _restaurantsCollection.UpdateOne(filter, addUpdate); // Remove duplicates from Grades array var pullUpdate = Builders<Restaurant>.Update .Pull(restaurant => restaurant.Grades, newGrades[0]); var result = _restaurantsCollection.UpdateOne(filter, pullUpdate); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); await _restaurantsCollection.UpdateOneAsync(filter, addUpdate); // Remove duplicates from Grades array var pullUpdate = Builders<Restaurant>.Update .Pull(restaurant => restaurant.Grades, newGrades[0]); var result = await _restaurantsCollection.UpdateOneAsync(filter, pullUpdate); return result;
여러 값의 모든 인스턴스
To 제거 all instances of more than one specific value from an 배열, call the Builders.Update.PullAll()
method. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
---|---|
| 데이터 유형: |
| 데이터 유형: |
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); _restaurantsCollection.UpdateOne(filter, addUpdate); // Remove duplicates from Grades array var gradesToRemove = new List<GradeEntry> { newGrades[0], newGrades[2] }; var pullUpdate = Builders<Restaurant>.Update .PullAll(restaurant => restaurant.Grades, gradesToRemove); var result = _restaurantsCollection.UpdateOne(filter, pullUpdate); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); await _restaurantsCollection.UpdateOneAsync(filter, addUpdate); // Remove duplicates from Grades array var gradesToRemove = new List<GradeEntry> { newGrades[0], newGrades[2] }; var pullUpdate = Builders<Restaurant>.Update .PullAll(restaurant => restaurant.Grades, gradesToRemove); var result = await _restaurantsCollection.UpdateOneAsync(filter, pullUpdate); return result;
조건과 일치하는 모든 값
To 제거 all values that match a specific condition from an 배열, call the Builders.Update.PullFilter()
method. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
---|---|
| 데이터 유형: |
| 데이터 유형: FilterDefinition<TItem> |
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); _restaurantsCollection.UpdateOne(filter, addUpdate); // Remove all "Grade = F" values from Grades array var pullUpdate = Builders<Restaurant>.Update .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); var result = _restaurantsCollection.UpdateOne(filter, pullUpdate); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); await _restaurantsCollection.UpdateOneAsync(filter, addUpdate); // Remove all "Grade = F" values from Grades array var pullUpdate = Builders<Restaurant>.Update .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); var result = await _restaurantsCollection.UpdateOneAsync(filter, pullUpdate); return result;
일치하는 값 업데이트
To 업데이트 a value in an 배열 필드, call the Builders.Update.Set()
method. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
---|---|
| 데이터 유형: |
| 데이터 유형: |
첫 번째 일치하는 값
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli") & Builders<Restaurant>.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders<Restaurant>.Update .Set("grades.$.score", 100); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
참고
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli") & Builders<Restaurant>.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders<Restaurant>.Update .Set("grades.$.score", 100); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
참고
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli") & Builders<Restaurant>.Filter.Eq("grades.grade", "A"); var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli") & Builders<Restaurant>.Filter.Eq("grades.grade", "A"); var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
일치하는 모든 값
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List<ArrayFilterDefinition> { new BsonDocumentArrayFilterDefinition<Restaurant>( new BsonDocument { { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders<Restaurant>.Update .Set("grades.$[gradeEntry].grade", "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = _restaurantsCollection.UpdateOne(filter, update, updateOptions); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List<ArrayFilterDefinition> { new BsonDocumentArrayFilterDefinition<Restaurant>( new BsonDocument { { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders<Restaurant>.Update .Set("grades.$[gradeEntry].grade", "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = await _restaurantsCollection.UpdateOneAsync(filter, update, updateOptions); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List<ArrayFilterDefinition> { new BsonDocumentArrayFilterDefinition<Restaurant>( new BsonDocument { { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Grade, "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = _restaurantsCollection.UpdateOne(filter, update, updateOptions); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List<ArrayFilterDefinition> { new BsonDocumentArrayFilterDefinition<Restaurant>( new BsonDocument { { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Grade, "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = await _restaurantsCollection.UpdateOneAsync(filter, update, updateOptions); return result;
All Values
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders<Restaurant>.Update .Set("grades.$[].score", 100); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders<Restaurant>.Update .Set("grades.$[].score", 100); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.AllElements().Score, 100); var result = _restaurantsCollection.UpdateOne(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.AllElements().Score, 100); var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result;
API 문서
이 가이드 에 설명된 메서드 또는 유형에 대한 자세한 내용은 다음 API 문서를 참조하세요.