Last active
September 10, 2015 12:45
-
-
Save Jim-Lin/24f165f434e415f1a519 to your computer and use it in GitHub Desktop.
[MongoDB .NET Driver] Upsert & SetOnInsert sample ref: http://qiita.com/SHUAI/items/e1f9bde6eb118de0fb88
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Member | |
{ | |
public ObjectId Id { get; set; } | |
public string PersonId { get; set; } | |
public string Name { get; set; } | |
public int Gender { get; set; } | |
public string Phone { get; set; } | |
public int ZipCode { get; set; } | |
public string Address { get; set; } | |
public DateTime CreatedDate { get; set; } | |
public DateTime ModifiedDate { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var filter = Builders<Member>.Filter.Eq<string>(m => m.PersonId, id); | |
var updates = new List<UpdateDefinition<Member>>(); | |
updates.Add(Builders<Member>.Update.Set(m => m.Phone, phone)); | |
updates.Add(Builders<Member>.Update.Set(m => m.ModifiedDate, DateTime.Now)); | |
// SetOnInsert: 只有新增時才會寫入其值 | |
updates.Add(Builders<Member>.Update.SetOnInsert(m => m.CreatedDate, DateTime.Now)); | |
// Upsert: UpdateOptions -> IsUpsert = true | |
var result = db.GetCollection<Member>(colName).UpdateOneAsync(filter, Builders<Member>.Update.Combine(updates), new UpdateOptions() { IsUpsert = true }).ConfigureAwait(continueOnCapturedContext: false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment